How to remove specific elements from an array in JS?

In this post, I provide a solution on how to remove specific elements from an array in JavaScript. Furthermore, I provide an example of how to extend the Array prototype in JavaScript.

Remove a specific element from an array

In the following example, I want to remove the number 3 from the array. Unfortunately, JavaScript does not provide a simple and intuitive way to do so, hence, first, the index of the element is retrieved by calling the indexOf method. Next, the splice method is called, which changes the contents of the array by removing the first element equal to 3.

var arr = [1, 2, 3, 4, 5, 1, 2, 3, 4, 5];

const elIdx = arr.indexOf(3);
if (elIdx > -1) {
  arr.splice(elIdx, 1);
}

console.log(arr); 

Result:

[1, 2, 4, 5, 1, 2, 3, 4, 5]

You will notice that only the first number 3 is removed from the array.

Remove multiple elements from an array

The example below loops through the array and removes the element which is equal to 3.

var arr = [1, 2, 3, 4, 5, 1, 2, 3, 4, 5];

for (let i = arr.length - 1; i >= 0; --i) {
    if (arr[i] === 3) {
        arr.splice(i, 1);
    }
}

console.log(arr); 

Result:

[1, 2, 4, 5, 1, 2, 4, 5]

Extend the Array prototype

Another solution is to extend the Array prototype:

Array.prototype.remove = function (el) {
    const elIdx = this.indexOf(el);
		if (elIdx > -1) {
  		this.splice(elIdx, 1);
		}
};

var arr = [1, 2, 3, 4, 5, 1, 2, 3, 4, 5];
arr.remove(3);

console.log(arr);  

Result:

[1, 2, 4, 5, 1, 2, 3, 4, 5]

In the same way, the removeAll method can be implemented to remove all the desired elements from the array.

Using Set

If your array has unique values, you can store the data using Set. It already includes the delete() method which removes a specified value from a Set. Be aware of the performance for both array and Set.

Leave a Reply