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

时间:2019-07-24 07:59:53

标签: 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"]

但是我需要的是梨和菠萝的原始索引位置的另一个数组,该数组将打印以下内容

[1,2]

我将如何实现这一目标?

4 个答案:

答案 0 :(得分:4)

filter不是过滤数组,而是keys

var x = ["Apple","Pear","Pineapple"],
    value ="P",
    regex = new RegExp(`^${value}`, 'i'),
    filtered = [...x.keys()].filter(i => regex.test(x[i]));

console.log(filtered)

keys()方法返回 Array Iterator 。因此,您需要使用spread syntaxArray.from()将其转换为数组

答案 1 :(得分:3)

您可以使用reduceread 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);

答案 2 :(得分:2)

您可以首先获取值/索引对,进行过滤并获取值或索引。

RegExp的中间,可以使用String#startsWith,它没有特殊含义的字符的问题。

var array = ["Apple", "Pear", "Pineapple"],
    value = 'P',
    filtered = array
        .sort()
        .map((v, i) => [v, i])
        .filter(([v]) => v.startsWith(value)),
    values = filtered.map(([v]) => v),
    indices = filtered.map(([, i]) => i);

console.log(values);
console.log(indices);

答案 3 :(得分:1)

我已经用模拟函数对正则表达式进行了替换,但是您可以使用indexOf()从原始数组中获取索引,如下所示:

var x = ["Apple","Pear","Pineapple"];

var filtered = x.sort().filter(v => v.indexOf('P') !== -1);
var filteredIndexes = filtered.map(v => x.indexOf(v))

console.log(filtered)
console.log(filteredIndexes)