pasztora
1/15/2020 - 3:03 PM

Handling lists/arrays in JavaScript

// Changing the element of a list
let groceryList = ['bread', 'tomatoes', 'milk'];
groceryList[1] = "avocados"

// Reassigning the whole list doesn't need let anymore
let groceryList = ['bread', 'tomatoes', 'milk'];
groceryList = ["ketchup"]

// Checking the length of an array or list
console.log(groceryList.length);

// Adding elements to the end of the list using the push method
const chores = ['wash dishes', 'do laundry', 'take out trash'];
chores.push("cook", "play");
console.log(chores); // Output: ['wash dishes', 'do laundry', 'take out trash', 'cook', 'play']

// Removing the last elemet of a list using the pop method
const chores = ['wash dishes', 'do laundry', 'take out trash'];
chores.pop(); // This method doesn't take any arguments

// Removing the first item of a list using shift
chores.shift()

// Adding an element to the beginning of the list
chores.unshift()

// Nested arrays
const numberClusters = [[1,2], [3,4], [5,6]]
const target = numberClusters[2][1] // accessing a list element

// Slicing a list by specifying the list element locations
console.log(groceryList.slice(1, 4));