我正在尝试聚合下面的数组(arr),以便得到如下的输出:
期望输出: [['2011-04-11','打开',6],['2011-04-11','关闭',4]]
但我得到了: 输出: [2011-04-11,Open:6,2011-04-11,Closed:4]
如何获取javascript数组映射并转换为所需的数据。
源代码摘录:
var arr = [
['2011-04-11', 'Open'],
['2011-04-11', 'Closed'],
['2011-04-11', 'Closed'],
['2011-04-11', 'Open'],
['2011-04-11', 'Open'],
['2011-04-11', 'Open'],
['2011-04-11', 'Closed'],
['2011-04-11', 'Closed'],
['2011-04-11', 'Open'],
['2011-04-11', 'Open']
];
var hist = [];
arr.map(function(a) {
if (a in hist)
hist[a]++;
else
hist[a] = 1;
});
答案 0 :(得分:5)
您可以改为使用[].reduce()
:
var result = function() {
var hist = {};
return arr.reduce(function(previous, current) {
if (current in hist) {
previous[hist[current]][2]++;
} else {
previous[hist[current] = previous.length] = current.concat(1);
}
return previous;
}, []);
}();
在reduce操作期间,它使用hist
来跟踪在正在构建的新数组中每个项目的位置。
如果该项目已存在,则会增加其频率元素(第三个元素)。如果该项目尚不存在,则会将其频率设置为1并将hist
更新为新项目的位置。