views:

1423

answers:

4

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.

+4  A: 

That's not what map does. You really want Array.filter. Or if you really want to remove the elements from the original list, you're going to need to do it imperatively with a for loop.

Patrick
+3  A: 

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]

olliej
+3  A: 
ggasp
A: 
var arr = [1,2,'xxx','yyy']

arr = arr.filter(function(e){ if(e != 'xxx') return true });

arr  // [1, 2, "yyy"]
vsync