Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS filter array on key

So an example could be:

let a = [10,20,30,40,50,60,70,80];
let b = [1,2,6];
console.log([a[1], a[2], a[6]);

which an explanation can be something like: get the objects of a which index is in b.

I know that i can do something like

const f = (a, b) => {
    let result = [];
    b.forEach(element => {
        result.push(a[element]);
    });
    return result;
}

But maybe there is a more concise way

EDIT: so far the best i can get is this

a.filter((n, index)=>b.includes(index)));

but is not the same, infact if b = [0,0,0] it does not returns [a[0],a[0],a[0]] but [a[0]]

like image 372
Alberto Sinigaglia Avatar asked Apr 15 '26 05:04

Alberto Sinigaglia


2 Answers

Iterate array b with Array.map() and return the value at the respective index from array a:

const a = [10,20,30,40,50,60,70,80];
const b = [1,2,6];

const result = b.map(index => a[index]);

console.log(result);
like image 156
Ori Drori Avatar answered Apr 17 '26 19:04

Ori Drori


The .from method of the global Array object lets you transform an array into a new array in a manner similar to .map().

let a = [10,20,30,40,50,60,70,80];
let b = [1,2,6];

let result = Array.from(b, n => a[n]);

console.log(result);

Because you want to convert b from indexes into values with a 1 to 1 relationship, some sort of "mapping" operation is what you're generally after.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!