对多维数组进行分组的更好方法 [英] A better way to group a multidimensional array
问题描述
下面的数据代表[行情,数量,单一值]
The data below represents a [ticker, amount, unitary value]
var data = [
['A', 140, 82.4],
['B', 100, 55.5],
['A', 30, 77.2],
['B', 200, 60.1]
];
如何对代码进行分组,并使用JavaScript的Map,Reduce和Filter在新的矩阵中(例如[ticker,金额,平均价格,总价值])计算平均价格和总价值:
How to group by ticker codes, and calculate the average price and total value, using JavaScript’s Map, Reduce, and Filter, in a new matrix like [ticker, amount, average price, total value]:
var newData = [
['A', 170, 81.482, 13852],
['B', 300, 58.566, 17570]]
];
这是到目前为止我尝试过的.有一种方法可以使这些代码在最短,更优雅的代码方面更有效?
Here is what I have tried so far. There are a way do to this code more efficient in terms of shortest, elegant code?
var newData = data.map(function(item) {
return data.filter(function(itemFilter) {
return itemFilter[0] == item[0];
})
.reduce(function(array, item) {
array[0] = item[0];
array[1] += item[1];
array[3] += (item[1] * item[2]);
array[2] = array[3] / array[1];
return array;
}, ['', 0, 0, 0]);
})
//Remove duplicate items
.filter(function(item, index, inputArray) {
return inputArray.map(function(item) {
return item[0];
}).indexOf(item[0]) == index;
});
推荐答案
您可以使用临时对象 this
引用结果数组 newData
并添加位置并以第一个项目为键 this [a [0]]
来计算数组的平均值.
You could use a temporary object this
for the reference to the result array newData
and add the positions and calculate the average at the array with the first item as key this[a[0]]
.
var data = [['A', 140, 82.4], ['B', 100, 55.5], ['A', 30, 77.2], ['B', 200, 60.1]],
newData = [];
data.forEach(function (a) {
var product = a[1] * a[2];
if (!this[a[0]]) {
this[a[0]] = [a[0], 0, 0, 0];
newData.push(this[a[0]]);
}
this[a[0]][1] += a[1];
this[a[0]][3] += product;
this[a[0]][2] = this[a[0]][3] / this[a[0]][1];
}, {});
document.write('<pre>' + JSON.stringify(newData, 0, 4) + '</pre>');
这篇关于对多维数组进行分组的更好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!