Home > Enterprise >  How to filter array referring to a list of strings and return only selected columns?
How to filter array referring to a list of strings and return only selected columns?

Time:02-22

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"]]

CodePudding user response:

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

CodePudding user response:

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(...)).

  • Related