Removing elements with Array.map in JavaScript

Vincent Robert picture Vincent Robert · Aug 13, 2008 · Viewed 101.9k times · Source

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.

Answer

olliej picture olliej · Aug 13, 2008

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]