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

3

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

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的原始索引位置,输出结果如下:

[1,2]

我该如何实现这个目标?


正则表达式在哪里? - briosheje
忘记添加了,现在已经加上了。 - ShaneOG97
也许你可以使用 var indices = filtered.map(f => x.indexOf(f));?因为你在 x 中保留了原始未修改的数组的副本。 - nbokmans
“value”在哪里? - briosheje
过滤 keys 而不是 values - jank
4个回答

5
您可以使用reduce在此处了解有关reduce的更多信息)一次性完成此操作。无需过滤,您只需生成另一个数组,并跟踪当前循环项的索引(假设您想要排序的索引)。
如果您不想要排序后的索引,请删除.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);


5

不要过滤数组,而是过滤数组的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.from()将其转换为数组。


3
您可以使用 indexOf() 从原始数组中获取您的索引,如下所示:

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

var regex = new RegExp(`^P`, 'i');

const filtered = x.sort().filter(v => regex.test(v));
const filteredIndexes = filtered.map(v => x.indexOf(v));

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

您还可以使用reduce方法一次迭代完成操作,如下所示:

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

var regex = new RegExp(`^P`, 'i');

const [filtered, filteredIndexes] = x.sort().reduce((acc, val, i) => {
  // If the regex fits, add to the arrays
  if(regex.test(val)) {
    // Adding to the array via array spread operator
    acc = [[...acc[0], val],[...acc[1], i]];
  }
  return acc;
}, [[],[]]); // Initial value of accumulator

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


3

您可以先获取值/索引对,然后筛选并获取值或索引。

不需要使用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);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接