如何通過另一個元素陣列過濾資料集。
var filterBy = ["apple", "orange", "grapes"];
var selectColsIdx = [0, 1]
var data = [[1, "orange", 20], [3, "grapes", 4], [6, "bananas", 9]];
我想將filterBy陣列作為過濾器應用于data資料集子陣列 (index 1) ,并輸出如下(其中僅回傳 0 和 1 的項索引:
res = [[1, "orange"], [3, "grapes"]]
uj5u.com熱心網友回復:
您可以Array#flatMap使用外部陣列的單個回圈。
const
filterBy = ["apple", "orange", "grapes"],
selectColsIdx = [0, 1],
data = [[1, "orange", 20], [3, "grapes", 4], [6, "bananas", 9]],
result = data.flatMap(a => filterBy.includes(a[1])
? [selectColsIdx.map(i => a[i])]
: []
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
具有兩個回圈的更經典的方法
const
filterBy = ["apple", "orange", "grapes"],
selectColsIdx = [0, 1],
data = [[1, "orange", 20], [3, "grapes", 4], [6, "bananas", 9]],
result = data
.filter(a => filterBy.includes(a[1]))
.map(a => selectColsIdx.map(i => a[i]));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
uj5u.com熱心網友回復:
如果我理解您的問題,您希望首先從更大的陣列中過濾某些子陣列,然后從每個子陣列中只提取幾個專案。
如果是這樣,可以這樣做:
const filterBy = ["apple", "orange", "grapes"]
const selectColsIdx = [0, 1]
const data = [[1, "orange", 20], [3, "grapes", 4], [6, "bananas", 9]]
// The Array.filter function takes a callback, where the callback takes (up to) three arguments: item, index and array.
// If a subArray gets a positive return value for the callback, it is kept.
// The Array.some function also takes a callback, and returns true if any of the subitems satisfies the callback.
// The Array.includes function simply returns true if the array contains (includes) the given item.
const output1 = data.filter(subArray => subArray.some(item => filterBy.includes(item)))
const output2 = output1.map(subArray => subArray.filter((item, index) => selectColsIdx.includes(index)))
console.log("data:", data)
console.log("output1:", output1)
console.log("output2:", output2)
.as-console-wrapper { max-height: 100% !important; top: 0; }
請注意,這些陣列函式(過濾器和映射)可以鏈接起來(如const output = data.filter(...).map(...))。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/429804.html
標籤:javascript 数组 筛选
