How to filter a dataset by another array of elements.
var filterBy = ["apple", "orange", "grapes"];
var selectColsIdx = [0, 1]
var data = [[1, "orange", 20], [3, "grapes", 4], [6, "bananas", 9]];
I want to apply the filterBy
array as filter to data
dataset sub arrays (index 1) , and output as follows (where only item index of 0 and 1 are returned:
res = [[1, "orange"], [3, "grapes"]]
>Solution :
You oculd take Array#flatMap
and a single loop of the outer array.
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; }
A more classig approach with two loops
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; }