如何获取过滤后的数组项的索引

How can I get the indexes of a filtered array items

我有这种情况,我有一个数组,我需要对它进行过滤并获取过滤项的索引,就像这个例子:

var arr = ['2022-05', '2023-01', '2022-04', '2022-02', '2023-08'];

我正在使用这个过滤器:

var filter = arr.filter(e => e.split("-")[0] == '2022'); //To get the values from 2022

我得到了这个结果:

filter = ['2022-05', '2022-04', '2022-02'];

我现在需要做的是获取这些项目的索引,所以它是这样的:

filter = ['2022-05', '2022-04', '2022-02'];
index = [0,2,3]

我该怎么做?谢谢

您可以使用 indexOf 方法:

filter.map(el => arr.indexOf(el));

您可以将条件检查提取到回调函数中(为简单起见),然后 reduce 遍历数组并将条件为 true 的索引推入累加器数组。

var arr = ['2022-05', '2023-01', '2022-04', '2022-02', '2023-08'];

const condition = (e) => e.split("-")[0] == '2022'

const filter = arr.filter(condition)
const indexes = arr.reduce((a,b,i) => (condition(b) ? a.push(i) : '', a), [])
console.log(filter, indexes)

在过滤数组之前,您可以将其映射到包含索引的新对象数组。

var arr = ['2022-05', '2023-01', '2022-04', '2022-02', '2023-08'];
var output = arr.map((value, index) => ({index, value}))
  .filter(e => e.value.split("-")[0] == '2022');

console.log(output);

匹配时,将需要的索引添加到数组中即可

 var arr = ['2022-05', '2023-01', '2022-04', '2022-02', '2023-08'];
    
var index = [];
var filter = arr.filter((e, indx) => {
  const flag = e.split("-")[0] == '2022';
  if (flag) {
    index.push(indx)
  }
  return flag;
});
console.log(filter)
console.log(index)