如何在javascript数组中搜索相同值的多个索引

Cap*_*ine 2 javascript arrays jquery

我有一个1维数组,如:

var abc = ['a','a','b','a','c']
Run Code Online (Sandbox Code Playgroud)

现在我想要取回所有索引'a',即0,1和3.

有没有简单的解决方案?

PS

我知道IndexOfjQuery.inArray().但他们只返回了第一个匹配元素的索引

Nin*_*olz 8

您可以使用Array#reducewithArray#concat检查所需的项目,获取索引或空数组。

var abc = ['a', 'a', 'b', 'a', 'c'],
    indices = abc.reduce((r, v, i) => r.concat(v === 'a' ? i : []), []);

console.log(indices);
Run Code Online (Sandbox Code Playgroud)

ES5

var abc = ['a', 'a', 'b', 'a', 'c'],
    indices = abc.reduce(function (r, v, i) {
        return r.concat(v === 'a' ? i : []);
    }, []);

console.log(indices);
Run Code Online (Sandbox Code Playgroud)


Mat*_*yas 7

您可以Array Object使用以下方法扩展基本:

Array.prototype.multiIndexOf = function (el) { 
    var idxs = [];
    for (var i = this.length - 1; i >= 0; i--) {
        if (this[i] === el) {
            idxs.unshift(i);
        }
    }
    return idxs;
};
Run Code Online (Sandbox Code Playgroud)

然后操作

var abc = ['a','a','b','a','c'];
abc.multiIndexOf('a');
Run Code Online (Sandbox Code Playgroud)

会给你结果:

[0, 1, 3]
Run Code Online (Sandbox Code Playgroud)

Jsperf比较 unshift/push/push(逆序)


Sas*_*olf 5

您可以结合使用 while 循环,而不是使用 for 循环indexOf

var array = [1, 2, 3, 4, 2, 8, 5],
    value = 2,
    i = -1,
    indizes = [];

while((i = array.indexOf(value, i + 1)) !== -1) {
    indizes.push(i);
}
Run Code Online (Sandbox Code Playgroud)

这将使您返回[1, 4],当然可以与扩展Array.

的第二个参数indexOf指定在给定数组中从何处开始搜索。