Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I filter an array of arrays using an array?

How do I filter an array of arrays (myNumbers) against an array (result) to get only the values that appear in result per each array in myNumbers?

Specifically, given:

var result = [02, 03, 04, 06, 07, 11, 12, 13];

var myNumbers = [
    [01, 03, 04, 05, 09, 10, 12, 14],
    [01, 03, 04, 05, 06, 08, 10, 12],
    [01, 02, 04, 05, 06, 08, 10, 12],
    [01, 03, 04, 05, 06, 09, 12, 13],
    [01, 02, 03, 05, 06, 08, 10, 11]
];

Output should be:

[
    [03, 04, 12],
    [03, 04, 06, 12],
    [02, 04, 06, 12],
    [03, 04, 06, 12, 13],
    [02, 03, 06, 11],
]

I'm only able to filter one array at a time:

// This only filters it for myNumbers[0]
var confereResult = result.filter(function (number) {
    if (myNumbers[0].indexOf(number) == -1)
            return number;
    console.log(number);
});

How do I go through the whole list instead?

like image 749
CodeG Avatar asked Jan 01 '23 07:01

CodeG


1 Answers

You could map the result of the filtering.

var filter = [02, 03, 04, 06, 07, 11, 12, 13],
    array = [[01, 03, 04, 05, 09, 10, 12, 14], [01, 03, 04, 05, 06, 08, 10, 12], [01, 02, 04, 05, 06, 08, 10, 12], [01, 03, 04, 05, 06, 09, 12, 13], [01, 02, 03, 05, 06, 08, 10, 11]],
    result = array.map(a => filter.filter(f => a.includes(f)));

console.log(result.map(a => a.join(' ')));
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 119
Nina Scholz Avatar answered Jan 05 '23 16:01

Nina Scholz