This is a quick summary on the most frequently-used array items removal scenarios in JavaScript.

Remove last element (i.e. remove from the end of an Array)

let arr     = [1, 2, 3, 4, 5, 6, 7];
let removed = arr.pop();

console.log(removed);
>> 7
console.log(arr); 
>> [1, 2, 3, 4, 5, 6]

Remove first element (i.e. remove from the beginning of an Array)

let arr     = [1, 2, 3, 4, 5, 6, 7];
let removed = arr.shift();

console.log(removed);
>> 1
console.log(arr); 
>> [2, 3, 4, 5, 6, 7]

Remove a range of adjacent elements

let arr     = [1, 2, 3, 4, 5, 6, 7];
let removed = arr.splice(2,3);

console.log(removed);
>> [3, 4, 5]
console.log(arr); 
>> [1, 2, 6, 7]

NOTE: arr.splice(start_index, number_of_removing_elements)

Remove a specific element by index

let arr     = [1, 2, 3, 4, 5, 6, 7];
let removed = arr.splice(2,1);

console.log(removed);
>> [3]
console.log(arr); 
>> [1, 2, 4, 5, 6, 7]

Remove a specific element by value

Case 1: when only 1 occurrence is present

let arr     = [1, 2, 3, 4, 5, 6, 7];
let removed = [];

for (let i = 0; i < arr.length; i++) { 
    if ( arr[i] === 5) { 
        removed = arr.splice(i, 1); 
    }
}

console.log(removed);
>> [5]
console.log(arr); 
>> [1, 2, 3, 4, 6, 7]

Case 2: when multiple occurrences are present

let arr     = [1, 5, 5, 2, 3, 1, 4, 5, 6, 2, 7, 5];
let removed = [];

for (let i = 0; i < arr.length; i++) { 
    if ( arr[i] === 5) { 
        removed.push(arr.splice(i, 1));
        i--;  
    }
}

console.log(removed);
>> [[5], [5], [5]]
console.log(arr); 
>> [1, 2, 3, 1, 4, 6, 2, 7]

NOTE: In the for loop, iteration index is decremented (i--) in order to handle adjacent element pairs with equal value. Without this line, your code would remove only one element and skip the other.

Remove elements programmatically by using a filter function

Method 1: using array.filter()

let arr      = [1, 2, 3, 4, 5, 6, 7];

let filtered = array.filter(function(value, index, arr) { return value > 5; });

console.log(filtered);
>> [6, 7]

NOTE: Using array.filter(), you can simply implement the behaviour of the remove operation (choosing some elements to keep and losing other elements). The special benefits are, the original array can be preserved unchanged (by reassigning to the same variable, you can achieve this if you want) and you can even apply some complex logic inside filter operation.

Method 2: using Lodash _.remove()

let arr      = [1, 2, 3, 4, 5, 6, 7];

let removed  = _.remove(array, function(n) { return n % 2 === 0; });

console.log(removed);
>> [2, 4, 6]
console.log(arr);
>> [1, 3, 5, 7]

Remove elements keeping array length unchanged

let arr      = [1, 2, 3, 4, 5, 6, 7];

delete arr[2]; // delete value at 2nd index 

console.log(arr);
>> [1, 2, empty, 4, 5, 6, 7]
console.log(arr[1])
>> 2
console.log(arr[2])
>> undefined
console.log(arr[3])
>> 4
console.log(arr.length);
>> 7

👉 Any questions? Please comment below.


Leave a comment