Home > other >  use array of indexes to filter another array javascript
use array of indexes to filter another array javascript

Time:10-18

I have 1 array and 1 set,set Indexes and array is Names.

Indexes contains various numbers which are basically indexes of random elements of Names array.I want to filter Names array based on indexes in Indexes array i.e push specific elements of Names array to another array whose indexes are present in the Indexes array.

What I am doing is:

const Indexes =[0,1]
const Names=["Test1","Test2","Test3","Test4"]

const filteredNames = Indexes.map(item => Names[item]);

Output should be:

filteredNames=["Test1","Test2"]

but its not working.Any leads on this?

CodePudding user response:

You almost had it right

const Indexes =[0,1]
const Names=["Test1","Test2","Test3","Test4"]

const filteredNames = Indexes.map(item => Names[item]);
console.log(filteredNames)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

it is also work with set

const Indexes =new Set([0,2]);
let temp=Array.from(Indexes);
const Names=["Test1","Test2","Test3","Test4"]

const filteredNames = temp.map(item => Names[item]);

console.log(filteredNames)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

If Indexes is a Set, then you just need Array.from function:

const Indexes =new Set([0,1])
const Names=["Test1","Test2","Test3","Test4"]

const filteredNames = Array.from(Indexes)
    .map(item => Names[item]);
  • Related