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

  1. push, MDN. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push˄

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

  1. pop, MDN. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop˄

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

  1. shift, MDN. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift˄

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

  1. unshift, MDN. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift˄

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
  1. concat
  2. every
  3. filter
  4. find
  5. findIndex
  6. forEach
  7. includes
  8. indexOf
  9. join
  10. map
  11. pop
  12. push
  13. reduce
  14. reverse
  15. shift
  16. slice
  17. some
  18. sort
  19. splice
  20. unshift