在最少的运行中查找并返回多个值的数组位置
function getAllIndexes(arr, val) {
var indexes = [], i = -1;
while ((i = arr.indexOf(val, i+1)) != -1){
indexes.push(i);
}
return indexes;
}
var Cars = ["Nano", "Volvo", "BMW", "Nano", "VW", "Nano"];
var indexes = getAllIndexes(Cars, "Nano");
//will return 0 3 5
如何搜索多个项目并在更短的时间内更快、更高效地返回位置
var indexes = getAllIndexes(Cars, ["Nano","BMW"]);
//should return 0 2 3 5 6
最佳答案
您需要一种不同的方法,因为您有多个值需要寻找。
您可以映射匹配项目的索引,或对未找到的项目采用 -1
以便稍后进行过滤运行。
const
getAllIndices = (array, needles) => array
.map((v, i) => needles.includes(v) ? i : -1)
.filter(i => i + 1);
var cars = ["Nano", "Volvo", "BMW", "Nano", "VW", "Nano"],
indices = getAllIndices(cars, ["Nano", "BMW"]);
console.log(indices);
ES5
function getAllIndices(array, needles) {
return array
.map(function (v, i) { return needles.indexOf(v) + 1 ? i : -1; })
.filter(function (i) { return i + 1; });
}
var cars = ["Nano", "Volvo", "BMW", "Nano", "VW", "Nano"],
indices = getAllIndices(cars, ["Nano", "BMW"]);
console.log(indices);
关于javascript - 在最少的运行中有效地查找并返回多个值的数组位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53571991/