To remove a particular element from an array in JavaScript, you can use the Array.splice()
method. The splice()
method changes the contents of an array by removing/replacing existing elements or adding new elements to the array.
For example, if we want to remove a single item from the index i
, then we can use:
// Remove one item from index i arr.splice(i, 1);
Similarly, if we want to remove multiple items from the index i
, then we have to pass that number as a second parameter.
For example, to remove n elements from the index i
we have to use:
// Remove n items from index i arr.splice(i, n);
Example 1: Remove a Single Element
// Characters array let chars = ['a', 'b', 'c', 'd', 'e']; // Remove 1 item from index 2 chars.splice(2, 1); console.log(chars) // Output: [ 'a', 'b', 'd', 'e' ]
Similarly, to remove multiple items from the index i, you have to pass the number of items to be removed as a second parameter to the splice()
method.
Example 2: Remove Multiple Elements
// Characters array let chars = ['a', 'b', 'c', 'd', 'e']; // Remove 2 items from index 3 chars.splice(3, 2); console.log(chars) // Output: [ 'a', 'b', 'c' ]
Example 3: Remove a Given Element
If you don’t know the index of the element to be removed from the array, you have to first find it using the Array.indexOf()
method.
The indexOf()
method checks if a given element is present in the array. If yes, then it returns the index of that element, otherwise, it returns -1.
Once, the index of the element is found, you can use the splice()
method to remove it from the array.
// Characters array let chars = ['a', 'b', 'c', 'd', 'e']; // Element to be removed let elem = 'd'; // Find index let index = chars.indexOf(elem); // Remove 1 item from index if(index!=-1) chars.splice(index, 1); console.log(chars); // Output: [ 'a', 'b', 'c', 'e' ]