How can I remove a specific item from an array?

0 like 0 dislike
15 views

I have an array of numbers, and I'm using the .push() method to add elements to it.

Is there a simple way to remove a specific element from an array?

The equivalent of something like -

array.remove(number);
by (550 points) | 15 views

1 Answer

0 like 0 dislike

The splice() method changes the contents of an array by removing existing elements and/or adding new elements.

const array = [2, 5, 9];
console.log(array);
const index = array.indexOf(5);
if (index > -1) {
  array.splice(index, 1);
}
// array = [2, 9]
console.log(array); 
by (1.2k points)

Related questions

0 like 0 dislike
2 answers
0 like 0 dislike
1 answer
0 like 0 dislike
1 answer
0 like 0 dislike
1 answer
asked May 21, 2019 by officialandrey
0 like 0 dislike
5 answers
asked Apr 9, 2019 by mamaanarhiya
110,608 questions
257,186 answers
0 comments
1,107 users