3

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

3 Answers 3

7

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

Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

2

Another way could be:

var out = [];
for(let x of b){
  out.push(a[x]);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.