Create totals array from two-dimensional array in Javascript -


say have 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 create second array contains:

  1. each name once
  2. a total each name
  3. an array of objects, each object representing item , 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 best way create totals array?

also, array of objects items , prices two-dimensional array if that's more efficient, this:

// [name, total_price, [ [item, price], [item, price], [item, price] ] ] 

you can use array.prototype.reduce. example of temporary map variable 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 = 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));


Comments

Popular posts from this blog

dns - How To Use Custom Nameserver On Free Cloudflare? -

qt - Passing a QObject to an Script function with QJSEngine? -

c# - Web API response xml language -