Array deletes in JavaScript
Array deletion is an often misunderstood concept in JavaScript, partly because there is so may different ways to do it. This post attempts to clear that up.
Firstly, the most obvious method of deletion via the delete keyword does not delete in the normal way you would expect:
const arr = [1,2,3,4,5]; delete arr[2] console.log(arr); // [ 1, 2, , 4, 5 ] console.log(arr[2]); // undefined
So it just sets it to undefined. To avoid this, Array.splice can be used:
const arr = [1,2,3,4,5]; arr.splice(arr, 2, 1); console.log(arr); // [ 1, 3, 4, 5 ] console.log(arr[2]); // 4
There is another more obscure way too:
const arr = [1,2,3,4,5]; arr.length = 4; console.log(arr); // [ 1, 2, 3, 4 ] arr.length = 1; console.log(arr); // [ 1 ]
I don’t think there are any reasons to use this method beyond stopping a forEach loop (or other callback based synchronous loops) early:
const arr = [1,2,3,4,5]; arr.forEach((element) => { console.log(element); if (element === 3) { arr.length = 0; } }); // 1 // 2 // 3
Which is a strange thing to do in the first place.
Finally, the deleted item can be searched for and removed. This is slower than Array.splice (since it needs to loop through the entire array), but it is easy to understand and does not mutate the original array:
const arr = [1,2,3,4,5]; const newArr = arr.filter((element) => element !== 3); console.log(arr); // [ 1, 2, 3, 4, 5 ] console.log(newArr); // [ 1, 2, 4, 5 ]
Github Location https://github.com/Jacob-Friesen/obscurejs/blob/master/2018/arrayDelete.js














