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:
- each name only once
- a total for each name
- an array of objects, each object representing an item and corresponding price.
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] ] ]