我有一个数组,它根据用户在搜索框中输入的内容进行过滤。
var x = ["Apple","Pear","Pineapple"];
var value = e.target.value;
var regex = new RegExp(`^${value}`, 'i');
var filtered = x.sort().filter(v => regex.test(v));
如果我在搜索框中输入“P”,控制台会打印出来
["Pear","Pineapple"]
然而,我需要的是 Pear 和 Pineapple 的 original 索引位置的另一个数组,它将打印以下内容
[1,2]
我将如何实现这一目标?
最佳答案
您可以使用 reduce
( read more about reduce here ) 一次完成。
不需要过滤,你可以只生成另一个数组,跟踪当前循环项的索引(假设你想要排序索引)。
如果您不需要排序索引,只需删除 .sort。不确定为什么它首先存在。 此解决方案需要单次迭代,这应该是最优的(只要您删除不需要的排序)。
var x = ["Apple","Pear","Pineapple"];
var value = 'P';
var regex = new RegExp(`^${value}`, 'i');
var filtered = x.sort().reduce((acc, next, i) => { // acc is the current accumulator (initially an empty array), next is looped item, i is item's index (what you want in the result).
return regex.test(next) && acc.push(i), acc // <-- if the regex test is successfull, `i` is pushed to the accumulator. In both cases (so, even if the regex fails) the accumulator is returned for the next iteration.
}, []); // <-- [] is the initial value of `acc`, which is a new empty array.
console.log(filtered);
关于javascript - 数组过滤后的原始索引位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57177997/