javascriptduplicatesarrayofarrays

find repeated values in array of arrays then sum the values of the repeated arrays


i have this array

const products = [
  ["orange", 1],
  ["apple", 2],
  ["apple", 1],
  ["lemon", 1],
  ["lemon", -1],
];

i want to get this result :

newArray = [
  ["orange", 1],
  ["apple", 3],
  ["lemon", 0],
];

so it finds repeated values between the arrays, then sums the second element of the repeated values.

so far i have written this:

const fruits = [];
const quantity = [];
const newArray = [];

products.forEach((fruit) => {
  fruits.push(fruit[0]);
  quantity.push(fruit[1]);
});

fruits.filter((item, index) => {
  if (fruits.indexOf(item) !== index) {
    const value = quantity[index] + quantity[index - 1];
    newArray.push([item, value]);
  }
});

and i get in the console

console.log(newArray);
// [ [ 'apple', 3 ], [ 'lemon', 0 ] ]

which is correct, nevertheless i'm missing :

['orange', 1 ]

cant find a way to resolve it or writing less code to find the result.


Solution

  • Another choice is to use reduce() function

    const products = [
      ["orange", 1],
      ["apple", 2],
      ["apple", 1],
      ["lemon", 1],
      ["lemon", -1],
    ];
    
    const result = products.reduce((acc,val) => {
      let obj = acc.find(a => a[0] == val[0])
      if(!!obj){
            obj[1] += val[1]
           }else{
            acc.push(val)
           }
      return acc
    },[])
    
    console.log(result)