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.

1

1 Answer 1

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.