4

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

1
  • 1
    do a bubble sort and loop through it :P Commented Feb 9, 2012 at 7:23

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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;    
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.