2

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.

2
  • 1
    Please try it, and post what you've tried when you ask a question Commented Sep 13, 2013 at 23:28
  • Posted what I have tried (and it worked) below the "Edit" Commented Sep 14, 2013 at 0:34

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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

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.