javascript 获取重复的数组索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18417728/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 11:50:10  来源:igfitidea点击:

Get the array index of duplicates

javascriptarrays

提问by qwertyuiop

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

在 JavaScript 数组中,如何获取重复字符串的索引?

Example:

例子:

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

Another example:

另一个例子:

My Array = ["abc","def","abc","xyz","def","abc"] 
//----> return 0,2,5("abc") and 1,4("def");

I have no idea how to do this. Thanks in advance for your help!

我不知道该怎么做。在此先感谢您的帮助!

回答by Ingo Bürk

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

回答by Felix Kling

Another less sophisticated approach:

另一种不太复杂的方法:

Iterate over the whole array and keep track of the index of each element. For this we need a string -> positionsmap. 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.

遍历整个数组并跟踪每个元素的索引。为此,我们需要一张string -> positions地图。对象是用于此目的的常用数据类型。键是数组的元素,值是数组中每个元素的索引/位置数组。

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:

现在您可以遍历映射并删除数组值长度为 1 的所有条目。这些元素在数组中只出现一次:

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

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

现在map包含string -> positions数组的所有重复元素的映射。例如,如果您的数组是["abc","def","abc","xyz","def","abc"],则map是形式的对象

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

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

您可以以任何您喜欢的方式进一步处理它。



Further reading:

进一步阅读:

回答by EricG

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;