1

If I had an array like:

var array = [[1,"GOOG",4],[1,"GOOG",6],[2,"GOOG",4],[2,"FB",4]];

Using javascript, how could I turn it into an array where all the items containing the same second value in array[i][1] (in the example the first 3 have the same value of GOOG and get their third value array[i][2] added together and combined resulting in the following array.

var array = [["GOOG",14],["FB",4]];

Edit: Actually I need all items matching array[i][1] added and combined.

MorningSleeper
  • 415
  • 1
  • 5
  • 13
  • Possible duplicate of [What is the most efficient method to groupby on a javascript array of objects?](http://stackoverflow.com/questions/14446511/what-is-the-most-efficient-method-to-groupby-on-a-javascript-array-of-objects) – PM 77-1 Feb 04 '17 at 01:59

1 Answers1

1

var array = [[1,"GOOG",4],[1,"GOOG",6],[2,"GOOG",4],[2,"FB",4]];

var result = array.reduce(function(acc, item) {
  // check if an item with the same second (item[1]) value already exist
  var index = -1;
  acc.forEach(function(e, i) {
    if(e[0] == item[1])
      index = i;
  });
  
  // if it does exist
  if (index != -1)
    acc[index][1] += item[2]; // add the value of the current item third value (item[2]) to it's second value (acc[index][1])
  // if it does not
  else
    acc.push([item[1], item[2]]); // push a new element

  return acc; // return the accumulator (see reduce docs)
}, []);

console.log(result);
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73