AnApprentice
AnApprentice

Reputation: 110970

How to get Underscore's map to only return based on a condition

I currently have the following:

flatArray = _.map(items, function(x){ return x.count; });

This returns an array like so:

[6,6,3,0,0,0,1,0]

How can I get just the # of items where count is Gt 0. In this case, how can I get just the number 4.

I'm using underscore and jQuery.

Upvotes: 3

Views: 2770

Answers (5)

S McCrohan
S McCrohan

Reputation: 6693

There are several ways to do this - here are two:

var cnt = _.filter(items, function(x) { return x.count > 0; }).length;

var cnt = _.reduce(items, function(count, item) { return count + (item.count > 0 ? 1 : 0); }, 0); 

Upvotes: 1

zerkms
zerkms

Reputation: 254916

var cnt = _.map(items, function(x){ return x.count; })
           .filter(function(i) { return i > 0; })
           .length;

JSFiddle: http://jsfiddle.net/cwF4X/1/

Upvotes: 1

deostroll
deostroll

Reputation: 11975

You can use filter():

Example as in the docs:

var evens = _.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });

Here evens will be an array of even numbers (num % 2 == 0 )

For your case to get the required count:

var count = _.map(items, function(x){ return x.count; })
               .filter(function(i) { return i > 0; })
               .length;

Upvotes: 1

joemeilinger
joemeilinger

Reputation: 791

You could do a _.reduce to get a count of items > 0:

_.reduce(items, function(m,x) { return m + (x > 0 ? 1: 0); });

Upvotes: 2

Kousha
Kousha

Reputation: 36209

May not be the best way, but

var flatArray = [];
_.each(items, function(x)
{
    if (x > 0) flatArray.push(x);
});

console.log(flatArray) // prints [6,6,3,1]

Upvotes: 1

Related Questions