Filter unique array values and sum in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose, we have an array of arrays like this −

const arr = [[12345, "product", "10"],[12345, "product", "15"],[1234567, "other", "10"]];

We are supposed to write a function that takes in one such array. Notice that all the subarrays have precisely three elements in them.

Our function should filter out that subarray which has a repeating value as its first element. Moreover, for the subarray, we remove we should add their third element to its existing nonrepeating counterpart.

So, for the above array, the output should look like −

const output = [[12345, "product", "25"],[1234567, "other", "10"]];

Example

The code for this will be −

const arr = [[12345, "product", "10"],[12345, "product", "15"],[1234567,
"other", "10"]];
const addSimilar = (arr = []) => {
   const res = [];
   const map = {};
   arr.forEach(el => {
      const [id, name, amount] = el;
      if(map.hasOwnProperty(id)){
         const newAmount = +amount + +res[map[id] - 1][2];
         res[map[id] - 1][2] = '' + newAmount;
      }else{
         map[id] = res.push(el);
      }
   });
   return res;
}
console.log(addSimilar(arr));

Output

And the output in the console will be −

[ [ 12345, 'product', '25' ], [ 1234567, 'other', '10' ] ]
raja
Published on 21-Nov-2020 09:30:13
Advertisements