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.
const fruits = ["apple π", "banana π", "orange π", "grapes π"]
fruits.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
console.log(fruits) // π ['apple π', 'banana π', 'grapes π']
If you want to find an item and then delete it, you can use the following code:
const numbers = [1, 2, 3, 4, 5]
const index = numbers.indexOf(3)
if (index > -1) {
numbers.splice(index, 1)
}
console.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:
const numbers = [1, 2, 2, 3, 4, 2, 5]
for (i = numbers.length - 1; i >= 0; i--) {
if (numbers[i] === 2) {
numbers.splice(i, 1)
}
}
console.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.
const numbers = [1, 2, 3, 4, 5]
delete numbers[2]
console.log(numbers) // [1, 2, empty, 4, 5]
You could also assign undefined to remove the item and leave the slot.
const numbers = [1, 2, 3, 4, 5]
numbers[2] = undefined
console.log(numbers) // [1, 2, undefined, 4, 5]
Top comments (1)
Hi.
Please add an RSS feed for codingdeft.com's blog.
Also its comment section doesn't work ("An unexpected error happened"), so I'm commenting here.
Thank you.