Arrays Flashcards
Mutable
JS arrays are mutable - meaning the values they contain can be changed
Even if declared using const, values can be manipulated with .push() and .pop()
.length
Indicates the number of elements the array contains
Index
Array elements are indexed, starting with 0
Elements can be accessed by their index like this:
let array = [1, 2, 3]
array[0]; //1
array[1]; //2
array[3]; //3
.push() method
Appends one or more elements to the end of an array and returns the new length
const list = [1, 2, 3, 4, 5];
list.push(6); // 6
list; // [1, 2, 3, 4, 5, 6]
.pop() method
Removes the last element from an array and returns that element
const list = [1, 2, 3, 4, 5];
list.pop(); // 5
list; // [1, 2, 3, 4]
.map()
Returns a new array with the results of calling a provided function on every element in the given array
const list = [1, 2, 3, 4];
list.map((el) => el * 2); // [2, 4, 6, 8]
.filter()
Returns a new array with all elements that pass the test implemented by the provided function
const list = [1, 2, 3, 4];
list.filter((el) => el % 2 === 0); // [2, 4]
.reduce()
Reduce the array to a single value. The value returned is stored in an accumulator (result/total)
const list = [1, 2, 3, 4, 5];
list.reduce((total, item) => total + item, 0); // 15
.fill()
Fill the elements in an array with a static value
const list = [1, 2, 3, 4, 5];
list.fill(0); // [0, 0, 0, 0, 0]
.find()
Returns the value of the first element in the array that satisfies the provided testing function, otherwise returns undefined
const list = [1, 2, 3, 4, 5];
list.find((el) => el === 3); // 3
list.find((el) => el === 6); // undefined
.indexOf()
Returns the first index at which a given element can be found in the array, else returns -1
const list = [1, 2, 3, 4, 5];
list.indexOf(3); // 2
list.indexOf(6); // -1
.includes()
Returns true if the given element is present in the array
const list = [1, 2, 3, 4, 5];
list.includes(3); // true
list.includes(6); // false
.shift()
Removes the first element of the array and returns that element
const list = [1, 2, 3, 4, 5];
list.shift(); // 1
list; // [2, 3, 4, 5]