Get the array index of duplicates

前端 未结 3 1028
太阳男子
太阳男子 2020-12-29 13:55

In a JavaScript array how can I get the index of duplicate strings?

Example:

MyArray = [\"abc\",\"def\",\"abc\"]; //----> return 0,2(\"abc\");
         


        
3条回答
  •  太阳男子
    2020-12-29 14:52

    Yet another approach:

    Array.prototype.getDuplicates = function () {
        var duplicates = {};
        for (var i = 0; i < this.length; i++) {
            if(duplicates.hasOwnProperty(this[i])) {
                duplicates[this[i]].push(i);
            } else if (this.lastIndexOf(this[i]) !== i) {
                duplicates[this[i]] = [i];
            }
        }
    
        return duplicates;
    };
    

    It returns an object where the keys are the duplicate entries and the values are an array with their indices, i.e.

    ["abc","def","abc"].getDuplicates() -> { "abc": [0, 2] }
    

提交回复
热议问题