up vote 0 down vote favorite
share [fb]

What would be a nice algorithm to remove dupes on an array like below...

    var allwords = [

    ['3-hidroxitiramina', '3-hidroxitiramina'],

    ['3-hidroxitiramina', '3-hidroxitiramina'],

    ['3-in-1 block', 'bloqueo 3 en 1'],

    ['abacterial', 'abacteriano'],

    ['abacteriano', 'abacteriano'],

    ['abciximab', 'abciximab'],

...

Just to clarify, I would want one of the

['3-hidroxitiramina', '3-hidroxitiramina'],

To be removed, so there is just one

link|improve this question

61% accept rate
What exactly do you mean by duplicates in this example? Duplicate elements in the first dimension or in the second? – Gumbo Feb 6 '09 at 11:10
Made an edit to clarify – qui Feb 6 '09 at 11:14
According to the yet given answers, it’s quite not clear enough. I assume you want to remove the duplicates in the first dimension so that there’s just one “['3-hidroxitiramina', '3-hidroxitiramina']” in the array left, right? – Gumbo Feb 6 '09 at 11:36
feedback

3 Answers

up vote 1 down vote accepted

[edit]: misread, after reading your clarification I'd suggest:

 var i = allwords.length-1, prev='';
 do {
     if (allwords[i].join('/') === prev) {
    	allwords.splice(i,1);
     }
     prev = allwords[i].join('/');
 } while (i-- && i>-1);

(reversing the loop is a optimization step)

link|improve this answer
This seems to do the trick, thanks :) – qui Feb 6 '09 at 11:56
feedback

Try this:

var len = allwords.length, i, j, first;
for (i=0; i<len-1; i++) {
    first = allwords[i].toString();
    for (j=i+1; j<len; j++) {
        if (first === allwords[j].toString()) {
            allwords.splice(j, 1);
            len--;
        }
    }
}
link|improve this answer
feedback

You could use an object as an associative array/hash (If you mean dups in the first dimension)

var allWordsObj = {};
for( var i = 0; i < allWords.length; i++ ) {
    allWordsObj[allWords[i][0]] = allWords[i][1];
}

alert( allWordsObj['3-hidroxitiramina'] );
link|improve this answer
I dont, but thanks – qui Feb 6 '09 at 11:23
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.