[英]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.