Removing items from an array
suggest changeShift
Use .shift to remove the first item of an array.
For example:
const array = [1, 2, 3, 4];
array.shift();
array results in:
[2, 3, 4]
Pop
Further .pop is used to remove the last item from an array.
For example:
const array = [1, 2, 3];
array.pop();
array results in:
[1, 2]
Both methods return the removed item. On an empty array they return undefined.
Splice
Use .splice() to remove a series of elements from an array. .splice() accepts two parameters, the starting index, and an optional number of elements to delete. If the second parameter is left out .splice() will remove all elements from the starting index through the end of the array.
For example:
const array = [1, 2, 3, 4];
array.splice(1, 2);
leaves array containing:
[1, 4]
The return of array.splice() is a new array containing the removed elements. For the example above, the return would be:
[2, 3]
Thus, omitting the second parameter effectively splits the array into two arrays, with the original ending before the index specified:
const array = [1, 2, 3, 4];
array.splice(2);
…leaves array containing [1, 2] and returns [3, 4].
Delete
Use delete to remove item from array without changing the length of array:
const array = [1, 2, 3, 4, 5];
console.log(array.length); // 5
delete array[2];
console.log(2 in array); // false, a hole, not the value undefined
console.log(array.length); // 5
console.log(array[2]); // undefined when the hole is read
Array.prototype.length
Assigning a smaller length deletes items from the end.
const array = [1, 2, 3, 4, 5];
array.length = 2;
console.log(array); // [1, 2]