EN
JavaScript - remove element from array by index
16 points
In JavaScript, it is not intuitive the first time how to remove elements by index. Removing the element by index operation can be achieved with Array.prototype.splice
method. This article is focused on how to do it.
Quick solution:
xxxxxxxxxx
1
array.splice(index, 1); // removes 1 element
Where:
array
- from this array, we want to remove an element,index
- removed element index,1
- means the number of removed elements.
xxxxxxxxxx
1
// index: 0 1 2 3
2
var array = ['a', 'b', 'c', 'd'];
3
4
var removedElements = array.splice(2, 1); // removes only 3rd element (index: 2, count: 1)
5
6
console.log(array);
7
console.log(removedElements);
Array.prototype.splice(index, count)
method:
- takes:
index
- starting from this index elements will be removed,count
- number of the elemnts to remove starting from index,- returns:
- array with removed elements
- warning:
splice()
method middifies array
xxxxxxxxxx
1
const removeItem = (array, index) => {
2
const items = array.splice(index, 1);
3
if (items.length > 0) {
4
return items[0];
5
}
6
return null;
7
};
8
9
10
// Usage example:
11
12
// index: 0 1 2 3
13
const array = ['a', 'b', 'c', 'd'];
14
15
const removedItem = removeItem(array, 2);
16
17
console.log(array);
18
console.log(removedItem);