问题描述
我正在尝试汇总下面的数组(arr),以便获得如下输出:
I'm trying to aggregate the array (arr) below so that I get an output such as:
所需的输出: [ ['2011-04-11','Open',6],['2011-04-11','Closed',4]]
Desired Output: [['2011-04-11','Open',6],['2011-04-11','Closed',4]]
但是我m得到:
输出: [2011-04-11,打开:6,2011-04-11,关闭:4]
but I'm getting:Output: [2011-04-11,Open: 6, 2011-04-11,Closed: 4]
如何获取javascript数组映射并转换为所需的输出。
How can I take the javascript array map and convert to desired out.
源代码摘录:
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;
});
推荐答案
您可以使用代替:
You can use [].reduce()
instead:
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
During the reduce operation, it uses hist
to keep track of where each item can be found in the new array that's being built.
如果该项目已经存在,它将增加其频率元素(第三个元素)。如果该商品尚不存在,则会将其频率设置为1,并将 hist
更新为新商品的位置。
If the item already exists, it will increase its frequency element (third element). If the item does not yet exist, it will set its frequency to 1 and update hist
to the position of the new item.
这篇关于Javascript数组映射2D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!