Links
Comment on page

Remove Item

4 methods to remove items from an Array in JavaScript

pop - Remove last element

pop() will remove and return the last element from the array.
const arr = [1,2,3];
const val = arr.pop();
console.log({arr, val});
Output:
{arr: [1,2], val: 3}

shift - Remove first element

shift() will remove and return the first element from the array.
const arr = [1,2,3];
const val = arr.shift();
console.log({arr, val});
Output:
{arr: [2,3], val: 1}

splice - Remove at index

splice(start, deleteCount) will remove deleteCount of elements starting at index start and returns an array containing the deleted elements.
  • start - the zero-based index at which to start.
  • deleteCount - an integer indicating the number of elements to remove.
const arr = [1,2,3];
const val = arr.splice(1,1);
console.log({arr, val});
Output:
{arr: [1,3], val: [2]}

filter - Remove by value

filter(callbackFn) will return a shallow copy of the array, filtered down to just the elements that pass the test implemented by callbackFn.
  • callbackFn - A function to execute for each element of the array that returns a truthy value to keep the value in the resulting array
const arr = [1,2,3];
const val = arr.filter((x) => x == 2);
console.log({arr, val});
Output:
{arr: [1,2, 3], val: [2]}
filter() does not modify the original array, but instead creates a shallow copy.
Last modified 1mo ago