[英]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]
我怎样才能做到这一点? 谢谢。
在过滤数组之前,您可以将其映射到包含索引的新对象数组。
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)
您可以使用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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.