Array Methods
Some of the methods that are available on every Array object can be used to add or remove from the array. Here are a few of them:
The push() method adds one or more elements to the end of an array and returns the new length of the array. 1
const names = ['Jack', 'Laura', 'Paul', 'Megan'];
names.push('Jill'); // => 5
names;
// => ['Jack', 'Laura', 'Paul', 'Megan', 'Jill']
Footnotes
The pop() method removes the last element from an array and returns that element. This method changes the length of the array.1
const names = ['Jack', 'Laura', 'Paul', 'Megan'];
names.pop(); // => 'Megan'
names;
// => ['Jack', 'Laura', 'Paul']
Footnotes
The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.1
const names = ['Jack', 'Laura', 'Paul', 'Megan'];
names.shift(); // => 'Jack'
names;
// => ['Laura', 'Paul', 'Megan']
Footnotes
The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.1
const names = ['Jack', 'Laura', 'Paul', 'Megan'];
names.unshift('Jill'); // => 5
names;
// => ['Jill', 'Jack', 'Laura', 'Paul', 'Megan']
Footnotes
Removes or replaces and/or adds new elements of an array.
It takes the following parameters:
- the index of the element where to start modifying the array
- the number of elements to delete
- the elements to insert in the array (optional)
splice returns the elements that have been removed.
const arr = ['1', '2', '5', '6'];
// Insert an element at index 2
arr.splice(2, 0, '3');
console.log(arr);
// => ['1', '2', '3', '5', '6']
// Remove 2 elements, starting at index 3 and insert 2 elements
const removed = arr.splice(3, 2, '4', '5');
console.log(removed);
// => ['5', '6']
console.log(arr);
// => ['1', '2', '3', '4', '5']
// Remove 1 element at index 1
arr.splice(1, 1);
console.log(arr);
// => ['1', '3', '4', '5']
References
Children