Combine unique items of an array of arrays while summing values - JavaScript


We have an array of array, each subarray contains exactly two elements, first is a string, a person name in this case and second is a integer, what we are required to do is combine all those subarrays that have their first element same and the second element should be a sum of the second elements of the common subarrays.

Following is our example array −

const example = [[
   'first',
   12
], [
   'second',
   19
], [
   'first',
   7
]];

Should be converted to the following

const example = [[
   'first',
   19
   ], [
      'second',
      19
   ]
];

Let’s say we write a function combineArray() that takes in the array as input and returns the combined array as output, the code for the same will be −

Example

const people = [
   ['Ram', 21],
   ['Mohan', 33],
   ['Vikram', 25],
   ['Mike', 29],
   ['Mohan', 41],
   ['Vikram', 26]
];
const combineArray = (people) => {
   const map = {};
   for(const index in people){
      const name = people[index][0];
      const prop = people[index][1];
      if(map[name]){
         map[name] += prop;
      }else{
         map[name] = prop;
      }
   }
   return Object.keys(map).map(key => [key, map[key]]);
}
console.log(combineArray(people));

Output

The output in the console will be −

[ [ 'Ram', 21 ], [ 'Mohan', 74 ], [ 'Vikram', 51 ], [ 'Mike', 29 ] ]

Understanding the combineArray function −

It iterates over the array, maps the name as key and prop as value in an object, making sure duplicate key gets added together, and lastly the object is converted into an array of array and returned.

The time complexity of this function is O(2n) which is often rounded to O(n) and the space complexity is O(n) as well.

Updated on: 18-Aug-2020

338 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements