[英]How to search for multiple index(es) of same values in javascript array
I have a 1 dimensional array like: 我有一个1维数组,如:
var abc = ['a','a','b','a','c']
Now I want to get back all the indexes of 'a'
, that is 0, 1 and 3. 现在我想找回
'a'
所有索引,即0,1和3。
Are there any simple solutions? 有没有简单的解决方案?
PS PS
I know IndexOf
or jQuery.inArray()
. 我知道
IndexOf
或jQuery.inArray()
。 But they just returned the index of first matched element only 但他们只返回了第一个匹配元素的索引
You could extend the basic Array
Object
with the following method: 您可以使用以下方法扩展基本
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;
};
Then the operation 然后操作
var abc = ['a','a','b','a','c'];
abc.multiIndexOf('a');
would give you the result: 会给你结果:
[0, 1, 3]
Jsperf comparison of unshift / push / push(reverse order) Jsperf比较 unshift / push / push(逆序)
Rather than using a for loop, you can use a while loop combined with indexOf
: 您可以使用与
indexOf
结合的while循环,而不是使用for循环:
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);
}
This will return you [1, 4]
and of course could be combined with extending the prototype of Array
. 这将返回
[1, 4]
,当然可以与扩展Array
的原型相结合。
The second argument of indexOf
specifies where to start the search in the given array. indexOf
的第二个参数指定在给定数组中开始搜索的位置。
AFAIK, there's no Javascript or jQuery function that does this in one step, you have to write a loop. AFAIK,没有Javascript或jQuery函数可以一步完成,你必须编写一个循环。
var indexes = [];
$.each(abc, function(i, val) {
if (val == "a") {
indexes.push(i);
}
}
这样做:
var abc = ['a','a','b','a','c'];
for (var i=0; i<abc.length; i++) {if(abc[i]=='a') {console.log(i)};}
You can take advantage of the fact that $.map() does not push values in its resulting array when the function you pass returns undefined
. 您可以利用$ .map()在您传递的函数返回
undefined
时不会在其结果数组中推送值的事实。
Therefore, you can write: 因此,你可以写:
var abc = ["a", "a", "b", "a", "c"];
var indices = $.map(abc, function(element, index) {
if (element == "a") {
return index;
}
});
You also use reduce function on the array and push the indexes to accumulated array, you need start with an empty array, the good thing about reduce is it's async and also time execution is faster than for loop, also it's a native function on array, look at the below, hope it's helping: 你还在数组上使用reduce函数并将索引推送到累积数组,你需要从一个空数组开始,关于reduce的好处是它是异步的,并且时间执行比for循环更快,它也是数组上的本机函数,看下面,希望它有所帮助:
var arr = [0, 1, 2, 3, 7, 2, 3, 4, 7, 8, 9, 2, 3];
function indexesOf(num) {
var reduced = arr.reduce(function(acc, val, ind, arr){
if(val === num){
acc.push(ind);
}
return acc;
}, []);
return reduced;
}
indexesOf(2); //[2, 5, 11]
If your array size is fixed, then you can find the first occurrence in the array using indexOf()
. 如果您的数组大小是固定的,那么您可以使用
indexOf()
在数组中找到第一个匹配项。 Use the found index value as starting point in indexOf()
to find an other occurrence. 使用找到的索引值作为
indexOf()
起始点来查找其他匹配项。
var firstOccurance = [your_array].indexOf(2)
var secondOccurance = [your_array].indexOf(2, firstOccurance + 1)
You could use Array#reduce
with Array#concat
with a check for the wanted item, take the index or an empty array. 您可以使用
Array#reduce
with Array#concat
检查所需项目,获取索引或空数组。
var abc = ['a', 'a', 'b', 'a', 'c'], indices = abc.reduce((r, v, i) => r.concat(v === 'a' ? i : []), []); console.log(indices);
ES5 ES5
var abc = ['a', 'a', 'b', 'a', 'c'], indices = abc.reduce(function (r, v, i) { return r.concat(v === 'a' ? i : []); }, []); console.log(indices);
With ES6 syntax you could go with forEach and the ternary operator : 使用ES6语法,您可以使用forEach和三元运算符:
const abc = ['a','a','b','a','c']
let matchingIndexes = []
abc.forEach( (currentItem, index) => {
currentItem === 'a' ? matchingIndexes.push(index) : null
})
console.log(matchingIndexes) // [0, 1, 3]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.