简体   繁体   English

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

[英]How can I get the indexes of a filtered array items

I have this situation, I have an array and I need to filter it and get the indexes of the filtered items, like this example:我有这种情况,我有一个数组,我需要过滤它并获取过滤项的索引,例如这个例子:

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

I'm using this filter:我正在使用这个过滤器:

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

And I get this result:我得到了这个结果:

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

What I need to do now is to get also the index of these items, so it would be this:我现在需要做的是获取这些项目的索引,所以它会是这样的:

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

How can I do that?我怎样才能做到这一点? Thanks.谢谢。

Before filtering the array you can map it to a new array of objects that include the 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);

when matched, just add the desired index to the array匹配时,只需将所需的索引添加到数组中

 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)

您可以使用indexOf方法:

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

You can extract the condition check into a callback function (for simplicity), then reduce over the array and push the indexes where the condition is true into the accumulator array.您可以将条件检查提取到回调函数中(为简单起见),然后对数组进行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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM