Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing elements with Array.map in JavaScript

I would like to filter an array of items by using the map() function. Here is a code snippet:

var filteredItems = items.map(function(item) {     if( ...some condition... )     {         return item;     } }); 

The problem is that filtered out items still uses space in the array and I would like to completely wipe them out.

Any idea?

EDIT: Thanks, I forgot about filter(), what I wanted is actually a filter() then a map().

EDIT2: Thanks for pointing that map() and filter() are not implemented in all browsers, although my specific code was not intended to run in a browser.

like image 421
Vincent Robert Avatar asked Aug 12 '08 22:08

Vincent Robert


People also ask

How do I remove a particular element from an array in JavaScript?

pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.

How do you remove an element from an array with value?

To remove an item from a given array by value, you need to get the index of that value by using the indexOf() function and then use the splice() function to remove the value from the array using its index.

How do you remove all occurrences of an element from an array in JavaScript?

splice() function. The splice() method in JavaScript is often used to in-place add or remove elements from an array. The idea is to find indexes of all the elements to be removed from an array and then remove each element from the array using the splice() method.


1 Answers

You should use the filter method rather than map unless you want to mutate the items in the array, in addition to filtering.

eg.

var filteredItems = items.filter(function(item) {     return ...some condition...; }); 

[Edit: Of course you could always do sourceArray.filter(...).map(...) to both filter and mutate]

like image 152
olliej Avatar answered Sep 18 '22 23:09

olliej