在Javascript中从2d数组中删除重复项

时间:2022-08-27 07:52:36

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

要删除,所以只有一个

3 个解决方案

#1


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

(扭转循环是一个优化步骤)

#2


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

#3


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

#1


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

(扭转循环是一个优化步骤)

#2


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

#3


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