12
131

How to remove element from Array JavaScript

Reading Time: 2 minutes

There are many ways to remove element from array in JavaScript. The ones that will be focus here are various ways you can remove them via JavaScript.

Here, we will split the methods into 2 category name immutable and mutative. Immutable method is such that the original array remain unchanged after the remove operation.

Immutable

  • Slice
  • Filter

Mutative

  • Splice
  • Pop
  • Shift

Let’s break down to show how each method works.

Slice

It sounds exactly like what it will do. Slicing will remove element based on index that you put in. However, it will not change the original array.

const array = [0,1,2,3,4];
const result1 = array.slice(0,1); // Keep only the first element
const result2 = array.slice(1); // Remove the first element
const result3 = array.slice(1,2); // Keep only the second element

console.log(array);
console.log(result1);
console.log(result2);
console.log(result3);

Result:

[0,1,2,3,4]
[0]
[1,2,3,4]
[1]

Filter

This is an ES6 method where the function will match the element to be remove and return an array without that particular element. Writing in ES5 is also possible.

const array = [0,1,2,3,4];
const removeValue = '2';
const result = array.filter(element => element !== removeValue);

console.log(array);
console.log(result);

Result:

[0,1,2,3,4]
[0,1,3,4]

Splice

Splice is a better method if you want to have both the list of removed elements and the result array use some where after processing.

const array1 = [0,1,2,3,4];
const array2 = [0,1,2,3,4];
const result1 = array1.splice(1);
const result2 = array2.splice(1,2);

console.log(array1);
console.log(result1);
console.log(array2);
console.log(result2);

Result

[0]         // array1
[1,2,3,4]   // result1
[0,3,4]     // array2
[1,2]       // result2

Pop

Pop is the easiest way to remove last element with a single line of code and no index declaration.

const array = [0,1,2,3,4];
array.pop();

console.log(array);

Result

[0,1,2,3]

Shift

Shift is the easiest way to remove first element with a single line of code and no index declaration.

const array = [0,1,2,3,4];
array.shift();

console.log(array);

Result

[1,2,3,4]

Conclusion

In conclusion, there are many ways you can use to remove element from array. Some of the method listed are easily readable while some is more complex in order to give you flexibility to remove complex combination.

For easier maintainable code in the long run, TechDevPillar will recommend you to use those methods that can be understand easily!

Show Comments

No Responses Yet

Leave a Reply