最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get Underscore's map to only return based on a condition - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share edited May 19, 2020 at 17:03 halfer 20.4k19 gold badges109 silver badges202 bronze badges asked Jul 16, 2014 at 1:27 AnApprenticeAnApprentice 111k202 gold badges637 silver badges1k bronze badges 1
  • 1 Apply .filter() + .length – zerkms Commented Jul 16, 2014 at 1:29
Add a ment  | 

5 Answers 5

Reset to default 2

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

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

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]

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;
var cnt = _.map(items, function(x){ return x.count; })
           .filter(function(i) { return i > 0; })
           .length;

JSFiddle: http://jsfiddle/cwF4X/1/

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); 
发布评论

评论列表(0)

  1. 暂无评论