Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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; }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading