Stan
Stan

Reputation: 1200

Merge duplicate array keys in a multidimensional array

So I want to have my 2D array with duplicate values (shown below) to merge where the email addresses are the same. The email would always be in the same position.

[['[email protected]', 64], ['[email protected]', 65], ['[email protected]', 66]]

My hope is that I can get a result of:

[['[email protected]', 64, 65], ['[email protected]', 66]]

I don't anticipate that the array will have a ton of values, so if the answer isn't crazy efficient, that's not a deal breaker.

Edit:

This is what I have tried, and it worked for me.

Somebody posted this answer earlier, and I really liked it, but then it was deleted. So I'm going to post it and see what others think. I take no props!

var a = [['[email protected]', 64], ['[email protected]', 65], ['[email protected]', 66]];
var map = {};
for(var i=0; i<a.length; i++) {
    if(a[i][0] in map) {
        map[a[i][0]].push(a[i][1]);
    } else {
        map[a[i][0]] = [a[i][1]];
    }
}
console.log(map);

this first portion does the actual removal of duplicates and converts to an object with the numbers in an array.

a.length = 0;
for(var p in map) {
   a.push([p].concat(map[p]));   
}
console.log(a);

This second part is optional. It converts the object back into an array.

Not sure who posted this, but I liked the way this was done.

Upvotes: 2

Views: 1714

Answers (2)

Samuel Poirier
Samuel Poirier

Reputation: 1250

Here is a quick way to do it:

function getIndex(a, email) {
    for (var i = 0; i < a.length; i++) {
        if (a[i][0] === email) {
            return i;
        }
    }
    return -1;
}

var a = [['[email protected]', 64], ['[email protected]', 65], ['[email protected]', 66]];

var b = []

for (var i = 0; i < a.length; i++) {
    var index = getIndex(b, a[i][0]);       
    if(index == -1){
        b.push(a[i]);
    }else{
        b[index].push(a[i][1]);
    }
};

console.log(b);

Upvotes: 0

Jakub Kotrs
Jakub Kotrs

Reputation: 6229

My input:

var list = [['[email protected]', 64], ['[email protected]', 65], ['[email protected]', 66]],
    output = [],
    helper = [],
    index;

for(var i = 0; i < list.length; i++) {
 index = helper.indexOf(list[i][0];
 if(index !== -1) {
  output[index].push(list[i][1]);
 } else {
  helper.push(list[i][0]);
  output.push(list[i]);
 }
}
console.log(output);

Upvotes: 2

Related Questions