EN
JavaScript - remove specific array item by index
3 points
In this short article, we would like to show how to remove an item by index from an array in JavaScript.
Quick solution:
xxxxxxxxxx
1
array.splice(itemIndex, 1); // removes item with index
xxxxxxxxxx
1
const removeItem = (array, index) => {
2
const removedItems = array.splice(index, 1);
3
if (removedItems.length > 0) {
4
return removedItems[0];
5
}
6
return undefined;
7
};
8
9
// Usage example:
10
11
// index: 0 1 2 3
12
const array = ['a', 'b', 'c', 'd'];
13
14
removeItem(array, 2); // removed 'c' item that has index 2
15
console.log(array); // a, b, d