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.
source share