如何过滤引用字符串列表的数组并只返回选定的列



如何通过另一个元素数组过滤数据集。

var filterBy = ["apple", "orange", "grapes"];
var selectColsIdx = [0, 1]
var data = [[1, "orange", 20], [3, "grapes", 4], [6, "bananas", 9]];

我想将filterBy数组作为过滤器应用于data数据集子数组(索引1(,并输出如下(其中只返回0和1的项索引:

res = [[1, "orange"], [3, "grapes"]]

您可以获得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; }

如果我理解您的问题,您希望首先从较大的数组中筛选某些子数组,然后从每个子数组中只提取几个项。

如果是这样的话,可以这样做:

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; }

请注意,这些数组函数(filter和map(可以被链接(如const output = data.filter(...).map(...)(。

最新更新