admin管理员组

文章数量:1334817

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

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

Share Improve this question edited Jun 19, 2020 at 23:52 Alberto asked Jun 19, 2020 at 23:44 AlbertoAlberto 12.9k3 gold badges28 silver badges65 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 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);

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.

Another way could be:

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

本文标签: javascriptJS filter array on keyStack Overflow