[英]Create totals array from two-dimensional array in Javascript
Say I have this two-dimensional array: 说我有这个二维数组:
// [name, item, price]
var arr = [
['bob', 'book', '3'],
['mary', 'pencil', '2'],
['steve', 'book', '2'],
['steve', 'pencil', '1'],
['bob', 'book', '2']
];
I need to create a second array which contains: 我需要创建另一个包含以下内容的数组:
For instance: 例如:
// [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 } ] ]
];
What is the best way to create that totals array? 创建该合计数组的最佳方法是什么?
Also, the array of objects with the items and prices could even just be a two-dimensional array if that's more efficient, like this: 另外,如果商品和价格的对象数组更有效,甚至可以是一个二维数组,如下所示:
// [name, total_price, [ [item, price], [item, price], [item, price] ] ]
You can use Array.prototype.reduce . 您可以使用Array.prototype.reduce 。 For example with help of temporary map variable to store array indexes:
例如,借助临时映射变量来存储数组索引:
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));
There you go =) 你去=)
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); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.