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

131 views Asked by At

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.

3

There are 3 answers

0
flyingfox On BEST ANSWER

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)

0
CertainPerformance On

Group into an object, where the fruit name is a key and the value is the sum for that fruit found so far, then turn it back into an array of arrays afterwards.

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

const grouped = {};
for (const [fruit, quantity] of products) {
  grouped[fruit] = (grouped[fruit] ?? 0) + quantity;
}
const result = Object.entries(grouped);
console.log(result);

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

const flatten = products.flatMap(item => item);

const object = {}

for (let index = 0; index < flatten.length; index++) {
    if ( index % 2 === 0){
        const element = flatten[index];
        const quantity = flatten[index + 1];
        if(object[element]){
            object[element] = object[element] + quantity
        } else {
            object[element] =  quantity
        }
    }
}

const newArray = []

Object.entries(object).forEach(([fruit,quantity]) => {
    newArray.push(`['${fruit}',${quantity}]`)
})

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