How to Preserve an Array's Indexes in JavaScript When Deleting Array Elements?

Let's suppose we have the following array of numbers:

const nums = [ 0, 1, 2, 3, 4, 5 ];

In the following topics we will show you how you can remove array elements without re-arranging the array's indexes after removal (i.e. leaving holes/gaps in place where the elements are deleted):

Using the delete Operator

The delete operator removes the array element — i.e. after deletion there's nothing there. Outputting the array might show "empty" (which itself is not a type, but rather a way of describing that there's nothing there). For example:

delete nums[2];
delete nums[5];

console.log(nums); // output: [0, 1, empty, 3, 4, empty]
console.log(nums.length); // output: 6

As you can see, this preserves the array's indexes whilst deleting the values we wanted to remove.

It is important to note that the word "empty" is a mere representation of complete lack of a value, and it is not the same as undefined or null. Accessing the deleted array index, however, will return you undefined as a value. For example:

console.log(nums[2]); // output: undefined

Another important thing to note about "empty" is that the empty values are ignored by non-index-based iterators. For example:

nums.map(num => {
    console.log(num); // output: 0, 1, 3, 4
});

Compare it with an index-based loop, where the loop would iterate over the deleted indexes as well:

for (let i=0; i<nums.length; i++) {
    console.log(nums[i]); // output: 0, 1, undefined, 3, 4, undefined
}

Assigning null or undefined

Another approach could be to simply assign null or undefined as the value at the index you wish to delete. For example:

nums[2] = undefined;
nums[5] = null;

console.log(nums); // output: [0, 1, undefined, 3, 4, null]
console.log(nums.length); // output: 6

As you can see, this preserves the array's indexes as we're merely setting the values to null and undefined. The noticable difference between this approach and using the delete operator, however, is the fact that the index-based loops and other iterators would work all the same (i.e. they would all iterate over all the indexes including the ones with undefined and null values). For example:

nums.map(num => {
    console.log(num); // output: 0, 1, undefined, 3, 4, null
});
for (let i=0; i<nums.length; i++) {
    console.log(nums[i]); // output: 0, 1, undefined, 3, 4, null
}

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.