获取重复的数组索引 [英] Get the array index of duplicates
本文介绍了获取重复的数组索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在JavaScript数组我如何能得到重复的字符串的索引?
In a JavaScript array how can I get the index of duplicate strings?
例如:
MyArray = ["abc","def","abc"]; //----> return 0,2("abc");
另外一个例子:
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!
推荐答案
另一种方法:
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] }
这篇关于获取重复的数组索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文