Javascript merging an array if there is a duplicate value

var arr = [[7, 50], [7, 60], [8, 40]];

How to combine this array to be the result? [[7, 110], [8.40]];

lets say that if I have more than a hundred smaller arrays wrapped in an array

+4
source share
2 answers

I recommend using a map to store the results, not an array. Here is the O (n) solution:

var arr = [[7,50], [7,60], [8,40]]; function merge_array(arr) { var map = {}; for (var i = 0;i<arr.length;i++) { if (arr[i][0] in map) { map[arr[i][0]] += arr[i][1]; } else { map[arr[i][0]] = arr[i][1]; } } return map; } 

And if you are configured on an array as output, you can convert it.

+5
source

Here is the O (n) solution with the result of the array:

 function merge(arr){ var map = {}; var key; //Constructing the map for ( var i = 0 ; i < arr.length ; i++ ) { key = arr[i][0]; if ( typeof map[key] != 'undefined' ){ map[key] += arr[i][1]; } else { map[key] = arr[i][1]; } } //Converting the map to an array var result = []; for ( key in map ){ result.push( [key, map[key]] ); } return result; } 
+1
source

Source: https://habr.com/ru/post/1395552/


All Articles