Skip to content
javascript

How to remove a specific item from an array in JavaScript

Nov 26, 2022Abhishek EH2 Min Read
How to remove a specific item from an array in JavaScript

There are multiple ways in which an item from an array can be removed.

Using splice method

If you don't want the empty slot in the array and want the items on the right of the item to be removed to shift to the left, you can use the splice method.

1const fruits = ["apple 🍎", "banana 🍌", "orange 🍊", "grapes 🍇"]
2fruits.splice(2, 1) //first parameter is the index of the item to be removed. The second one is the number of items to be removed
3console.log(fruits) // 👉 ['apple 🍎', 'banana 🍌', 'grapes 🍇']

If you want to find an item and then delete it, you can use the following code:

1const numbers = [1, 2, 3, 4, 5]
2const index = numbers.indexOf(3)
3
4if (index > -1) {
5 numbers.splice(index, 1)
6}
7console.log(numbers) // 👉 [1, 2, 4, 5]

If you want to remove all the occurrences of an item from the array, you can loop the array as shown below:

1const numbers = [1, 2, 2, 3, 4, 2, 5]
2
3for (i = numbers.length - 1; i >= 0; i--) {
4 if (numbers[i] === 2) {
5 numbers.splice(i, 1)
6 }
7}
8
9console.log(numbers) //[1, 3, 4, 5]

We are looping the array in reverse from the right as the array length reduces and items shift toward the left. If we loop from the left, there are chances that we will miss the items.

Using delete keyword

If you want to leave the slot which was holding the item, then you can use the delete keyword.

1const numbers = [1, 2, 3, 4, 5]
2delete numbers[2]
3console.log(numbers) // [1, 2, empty, 4, 5]

You could also assign undefined to remove the item and leave the slot.

1const numbers = [1, 2, 3, 4, 5]
2numbers[2] = undefined
3console.log(numbers) // [1, 2, undefined, 4, 5]

If you have liked article, do follow me on twitter to get more real time updates!

Leave a Comment

© 2023 CodingDeft.Com