Get the array index of duplicates

前端 未结 3 1002
太阳男子
太阳男子 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] }
    
    0 讨论(0)
  • 2020-12-29 14:53

    Another less sophisticated approach:

    Iterate over the whole array and keep track of the index of each element. For this we need a string -> positions map. An object is the usual data type to use for this. The keys are the elements of the array and the values are arrays of indexes/positions of each element in the array.

    var map = {};
    
    for (var i = 0; i < arr.length; i++) {
        var element = arr[i];  // arr[i] is the element in the array at position i
    
        // if we haven't seen the element yet, 
        // we have to create a new entry in the map
        if (!map[element]) {
            map[element] = [i];
        }
        else {
           // otherwise append to the existing array
            map[element].push(i);
        }
        // the whole if - else statement can be shortend to
        // (map[element] || (map[element] = [])).push(i)
    }
    

    Now you can iterate over the map and remove all entries where the array value has a length of one. Those are elements that appear only once in an array:

    for (var element in map) {
        if (map[element].length === 1) {
            delete map[element];
        }
    }
    

    Now map contains a string -> positions mapping of all duplicate elements of the array. For example, if you array is ["abc","def","abc","xyz","def","abc"], then map is an object of the form

    var map = {
        'abc': [0,2,5],
        'def': [1,4]
    };
    

    and you can process it further in any way you like.


    Further reading:

    • Eloquent JavaScript - Data structures: Objects and Arrays
    • MDN - Working with objects
    • MDN - Predefined core objects, Array object
    0 讨论(0)
  • 2020-12-29 14:54

    This covers finding the indices efficiently:

    var inputArray = [1, 2, 3, 4, 5, 6, 6, 7, 8, 9];
    var encounteredIndices = {};
    
    for(var i = 0; i < inputArray.length; i++)
      if (encounteredIndices[inputArray[i]])
        console.log(i); // Or add to some array if you wish
      else
        encounteredIndices[inputArray[i]] = 1;
    
    0 讨论(0)
提交回复
热议问题