Arrays have many methods that perform different tasks.
.push()
allows us to add items to the end of an array.
For example, we add numbers 4 and 5 to the array
const numbers = [1, 2, 3];
numbers.push(4, 5);
console.log(numbers);
// Output: [1, 2, 3, 4, 5]
.pop()
removes the last item of an array.
const numbers = [1, 2, 3];
const removed = numbers.pop();
console.log(numbers);
// Output: [1, 2]
console.log(removed);
// Output: 3
shift()
method removes the first element from an array and returns that removed element. This method changes the length of the array.
const array1 = [1, 2, 3, 4, 5];
const firstElement = array1.shift();
console.log(array1);
// Output: [2, 3, 4, 5]
console.log(firstElement);
// Output: 1
The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.
const array1 = [1, 2, 3];
console.log(array1.unshift(4, 5));
// Output: 5
console.log(array1);
// Output: Array [4, 5, 1, 2, 3]
splice() method removes or replaces existing elements and/or adds new elements in place.
array.splice(indexToStart, numberOfIndices, "stringToAdd");
For example:
const months = ["Jan", "March", "April", "May"];
months.splice(1, 0, "Feb");
// inserts at index 1
console.log(months);
// Output: Array ["Jan", "Feb", "March", "April", "May"]
concat() method creates a new array by merging existing arrays.
let a = [1, 2];
let b = [3, 4, 5];
let c = a.concat(b);
slice() method slices out a piece of an array into a new array from start to end (end not included).
let array1 = [0, 1, 2, 3, 4, 5];
let num = array1.slice(1, 4);
// Output: [1, 2, 3]
reverse() method reverses the elements in an array. arr.reverse();
To check if something is an array, we use Array.isArray()
method
const numbers = [1, 2, 3];
console.log(Array.isArray(numbers)); // true
console.log(Array.isArray("hello")); // false because it's a string
To check the index of an item in an array, we use indexOf()
.
const names = ["Anna", "Pete", "Jane", "Luna"];
console.log(names.indexOf("Jane")); // 2