Remove an Element From an Array Using Filter in Nodejs

Friday, September 4, 2020 • One minute to read

to-the-point2020Nodejsarray

In nodejs, there are many options to remove an element from an array, one of them is using the filter.

filter method on array returns a new array based on the filtering condition.

For ex. return the even values in the array

1const arr1 = [1, 2, 3, 4, 5, 6];
2
3const arr2 = arr1.filter((n) => n % 2 === 0);
4
5console.log(arr2);

Output

[2, 4, 6]

Remove an element from the array

Remove 5 from the array.

1const arr1 = [1, 2, 3, 4, 5, 6];
2
3const arr2 = arr1.filter((n) => n != 5);
4
5console.log(arr1);
6console.log(arr2);

Output

1arr1: [1, 2, 3, 4, 5, 6];
2arr2: [1, 2, 3, 4, 6];

There are many other ways available in the nodejs to remove an element from the array, this method makes the code look clean and still get the job done.


to-the-point2020Nodejsarray

PreviousString Split in Golang

NextConvert Byte to Hex and Hex to Byte in Golang