How to remove an element from an array in JavaScript?
There are several ways to remove an element from an array in JavaScript:
- Using the
splice()
method: Thesplice()
method changes the contents of an array by removing or replacing existing elements and/or adding new elements. To remove an element from an array usingsplice()
, you need to specify the index of the element you want to remove and the number of elements to remove. Here's an example:
let arr = [1, 2, 3, 4, 5];
arr.splice(2, 1); // remove the element at index 2
console.log(arr); // [1, 2, 4, 5]
In the example above, arr.splice(2, 1)
removes the element at index 2 (which is the number 3) and the second argument 1
specifies that only one element should be removed.
- Using the
filter()
method: Thefilter()
method creates a new array with all elements that pass the test implemented by the provided function. To remove an element from an array usingfilter()
, you need to create a new array that excludes the element you want to remove. Here's an example:
let arr = [1, 2, 3, 4, 5];
arr = arr.filter(item => item !== 3); // remove the element with value 3
console.log(arr); // [1, 2, 4, 5]
In the example above, arr.filter(item => item !== 3)
creates a new array that includes all elements except the one with value 3.
- Using the
slice()
method: Theslice()
method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included). To remove an element from an array usingslice()
, you need to create a new array that excludes the element you want to remove. Here's an example:
let arr = [1, 2, 3, 4, 5];
arr = arr.slice(0, 2).concat(arr.slice(3)); // remove the element at index 2
console.log(arr); // [1, 2, 4, 5]
In the example above, arr.slice(0, 2)
returns a new array with the elements at index 0 and 1 (which are the numbers 1 and 2), and arr.slice(3)
returns a new array with the elements from index 3 to the end of the array (which are the numbers 4 and 5). The two arrays are then concatenated using the concat()
method to create a new array that excludes the element at index 2 (which is the number 3).