return 0,2("abc"); 另一个例子: -6ren">
gpt4 book ai didi

javascript - 获取重复项的数组索引

转载 作者:数据小太阳 更新时间:2023-10-29 05:46:47 25 4
gpt4 key购买 nike

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

示例:

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");

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

最佳答案

更新 01/2022:现在已经不是 2013 年了,很多事情都发生了变化。我既不建议修改原型(prototype),这个答案中的方法也不是“最佳”方法,因为它需要对数组进行多次迭代。

这是原始答案的更新版本,保留了它的精神,以及下面的原始答案。

function getDuplicates<T>(input: T[]): Map<T, number[]> {
return input.reduce((output, element, idx) => {
const recordedDuplicates = output.get(element);
if (recordedDuplicates) {
output.set(element, [...recordedDuplicates, idx]);
} else if (input.lastIndexOf(element) !== idx) {
output.set(element, [idx]);
}

return output;
}, new Map<T, number[]>());
}

另一种方法:

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

它返回一个对象,其中的键是重复的条目,值是一个带有索引的数组,即

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

关于javascript - 获取重复项的数组索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18417728/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com