var arr = [[7, 50], [7, 60], [8, 40]];
how to merge this array to become the result like this ? [[7, 110], [8,40]];
lets say if i have over hundreds of these smaller arrays wrapped by an array
var arr = [[7, 50], [7, 60], [8, 40]];
how to merge this array to become the result like this ? [[7, 110], [8,40]];
lets say if i have over hundreds of these smaller arrays wrapped by an array
I recommend that you use a map to store the results rather than an array. Here is a 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 dead set on an array as output, you can then convert it.
Here is the O(n) solution with an array result:
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;
}