简体   繁体   中英

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:

  1. each name only once
  2. a total for each name
  3. 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] ] ]

You can use 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM