说我有这个二维数组:
// [name, item, price]
var arr = [
['bob', 'book', '3'],
['mary', 'pencil', '2'],
['steve', 'book', '2'],
['steve', 'pencil', '1'],
['bob', 'book', '2']
];
我需要创建一个包含以下内容的第二个数组:
例如:
// [name, total_price, [ { item: item, price: price } ] ]
totals = [
['bob', 5, [ { item: 'book', price: 3 }, { item: 'book', price: 2 } ] ],
['mary', 2, [ { item: 'pencil', price: 2 } ] ],
['steve', 3, [ { item: 'book', price: 2 }, { item: 'pencil', price: 1 } ] ]
];
创建总数组的最佳方法是什么?
此外,具有项目和价格的对象数组甚至可以只是一个二维数组,如果它更有效,如下所示:
// [name, total_price, [ [item, price], [item, price], [item, price] ] ]
答案 0 :(得分:1)
您可以使用Array.prototype.reduce。例如,借助临时map变量来存储数组索引:
var arr = [
['bob', 'book', '3'],
['mary', 'pencil', '2'],
['steve', 'book', '2'],
['steve', 'pencil', '1'],
['bob', 'book', '2']
];
var names = {};
var result = arr.reduce(function(prev, curr) {
if (names[curr[0]] === undefined) {
prev.push([curr[0], 0, []]);
names[curr[0]] = prev.length - 1;
}
var i = names[curr[0]];
prev[i][1] += Number(curr[2]);
prev[i][2].push({item: curr[1], price: curr[2]});
return prev;
}, []);
document.write('<pre>' + JSON.stringify(result, null, 4));
答案 1 :(得分:0)
你去=)
var arr = [
['bob', 'book', '3'],
['mary', 'pencil', '2'],
['steve', 'book', '2'],
['steve', 'pencil', '1'],
['bob', 'book', '2']
];
totals = [];
$(document).ready(function() {
console.log(arr);
console.log(totals);
$.each(arr, function(i, order) {
var inserted = false;
$.each(totals, function(j, totalsOrder) {
if (order[0] == totalsOrder[0]) {
totalsOrder[1] = totalsOrder[1] + parseInt(order[2]);
var item = {
item: order[1],
price: parseInt(order[2])
};
totalsOrder[2].push(item);
inserted = true;
}
});
if (!inserted) {
var totalsItem = [order[0], parseInt(order[2]),
[{
item: order[1],
price: parseInt(order[2])
}]
];
totals.push(totalsItem);
}
});
console.log(totals);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;