Removing elements with Array.map in JavaScript

Question :

Removing elements with Array.map in JavaScript,

Answer :

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.

Read More  Efficient JPEG Image Resizing in PHP

,

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]

That’s the answer Removing elements with Array.map in JavaScript, Hope this helps those looking for an answer. Then we suggest to do a search for the next question and find the answer only on our site.

Disclaimer :

Read More  What is the single most influential book every programmer should read?

The answers provided above are only to be used to guide the learning process. The questions above are open-ended questions, meaning that many answers are not fixed as above. I hope this article can be useful, Thank you