计算数组对象的出现 [英] Count occurrences of array objects

查看:99
本文介绍了计算数组对象的出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望基于不同数组中同一对象的出现创建一个计数数组.到目前为止,我的代码看起来像这样:

I'm looking to create an array of counts based on the occurrences of the same object within a different array. So far, my code looks like this:

var dates = [];
$.each(items, function (i, item) {
    dates.push(item.date);
});

返回:

['2013/03', '2013/03', '2012/01', '2012/11', '2012/09', '2012/09', '2012/09']

在那之后,我想得到一个看起来像这样的数组:

After that, I'd like to end up with an array that looks like this:

[2,1,1,3]

任何帮助将不胜感激!

Any help would be much appreciated!

推荐答案

我将使用键/值计数方法,其中日期是键,而值是它出现的次数,如下所示:

I would use a key/value counting approach where the date is the key and the value is the number of times it appears like so:

var counters = {};
$.each(dates, function(i, date) {
   counters[date] = counters[date] ? counters[date] + 1 : 1;
});

这种方法假设日期都将遵循相同的格式.

This approach assumes the dates will all be following identical formats of course.

http://jsfiddle.net/wMR9x/2/

然后您可以像这样遍历它,并将结果简单地加入另一个数组:

Then you can loop over it like so and simply join the results into another array:

var finalCounts = [];
var i = 0;
for(var key in counters)
    finalCounts[i++] = counters[key];

这篇关于计算数组对象的出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆