javascript - 数组过滤后的原始索引位置

标签 javascript

我有一个数组,它根据用户在搜索框中输入的内容进行过滤。

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/

相关文章:

javascript - 先按字母排序,再按数字排序

javascript - Access-Control-Allow-Origin 不允许 Origin null

javascript - 在 IE 上滚动 div 时触发模糊事件

javascript - 在输入字段发生任何变化时调用 jQuery 函数

javascript for ...在迭代器之谜中

javascript - JS 表单验证问题

Javascript正则表达式将网站上的所有链接从http转换为https

javascript - 为什么以下 JavaScript 中 bar 未定义?

javascript - jQuery.text() 不适用于 textarea 元素

Javascript 使用 tr id 更改 td 元素的样式