How to remove specific elements of an array from JavaScript

Asked 2 years ago, Updated 2 years ago, 40 views

There's an integer type array. I added an element to the .push() method. Isn't there the simplest way to remove certain elements of an array? array.remove(int); like this.

I'm not using any framework, I'm just using JavaScript.

array javascript

2022-09-21 19:05

1 Answers

First, find the index of the element that you want to erase.

var array = [2, 5, 9];
var index = array.indexOf(5);

However, indexOf is not supported on Internet Explorer 7 and 8.

if (index > -1) {
    array.splice(index, 1);
}

In this way, use splice to erase it. The second parameter in the splice indicates the number of elements to erase. The example above means that we're going to erase only one from the first parameter.


2022-09-21 19:05

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.