Remove item from an array without changing the indexes in JavaScript
Let's see 2 ways of removing an element from an array without changing the indexes of the other elements.
Remove item by marking it empty with undefined or null
You can define null
or undefined
as empty. So you replace the current item with one of these values.
This is how you would mark the second position of an array as empty
const arr = [4, 5, 6];
arr[1] = null;
if (arr[1] === null) console.log('The item is empty');
Remove item by marking the slot as empty
You can mark an array position (slot) as empty slot by using delete.
const arr = [4, 5, 6];
delete arr[1];
console.log(arr);
// The console...
// on chrome shows [4, empty, 6]
// on firefox shows [4, <1 empty slot>, 6]
How to differentiate between empty slot and undefined
When you access an empty slot, it shows undefined
:
const arr = [6, , undefined, 9];
console.log(arr); // [6, empty, undefined, 9] on chrome
console.log(arr[1]); // undefined
console.log(arr[2]); // undefined
So this way, you can't differentiate between an empty slot or a slot with undefined.
For that you can use the operator in
.
The in
operator checks if a specific index is part of an array:
const arr = [6, , undefined, 9];
// Is index 1 not an empty slot?
console.log(1 in arr); // false
// Is index 2 not an empty slot?
console.log(2 in arr); // true
Empty slots gotchas
Iterating through an array with empty slots works differently in several methods.
const arr = [10, , 30];
arr.map((i) => i); // [10, empty, 30]
arr.length; // 3
console.log(arr.filter((i) => i !== 10)); // [30] SKIPS empty slots!
console.log(Object.keys(arr)); // ["0", "2"] SKIPS empty slots!
console.log(Object.values(arr)); // [10, 30] SKIPS empty slots!
Questions
What's the output?
const arr = [5, 6, 7];
delete arr[2];
console.log(arr);
What's the output?
let r1 = [2, , 4].filter((i) => 'banana');
let r2= [2, undefined, 4].filter((i) => 'banana');
console.log(r1 r2)
What's the output?
let r1 = Object.keys([1, , 3]);
let r2 = Object.keys([1, undefined, 3]);
console.log(r1, r2);
What's the output?
let r1 = Object.values([7, , 8]);
let r2 = Object.values([7, undefined, 8]);
console.log(r1, r2);
What's the output?
const arr = [];
delete arr[1];
console.log(arr);
What's the output?
const arr = [10, , undefined];
console.log(0 in arr);
console.log(1 in arr);
console.log(2 in arr);
What's the output?
const arr = [10, , undefined];
console.log('0' in arr);
console.log('1' in arr);
console.log('2' in arr);
What's the output?
[, 20, 30].map((i) => i);
What's the output?
[undefined, 20, 30].map((i) => i);
What's the output?
[, 5, 6].map((i) => i * 10);
What's the output?
[8, undefined, 9].map((i) => i * 10);
What's the output?
const r1 = [8, undefined, 9].length;
const r2 = [8, , 9].length;
console.log(r1, r2);