'How to filter array referring to a list of strings and return only selected columns?
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 1:[1]
If I understand your question, you wish to first filter certain sub-arrays from a larger array, and then pluck only a few items from each sub-array.
If that is so, it can be done like so:
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; }
Note that these array functions (filter and map) could be chained (like const output = data.filter(...).map(...)).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sebastian |
