Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I create a new array from an original array making use of ONE MORE DIFFERENT ARRAY in Javascript?

Here are two simple arrays, one is an original list, the other is a selected index from the original one.
I just want to re-create a new array, based on the selected index array.

Here is my code.

const list = [{
    id: 0,
    name: "Ken"
},
{
    id: 1,
    name: "Ryu"
},
{
    id: 2,
    name: "Sakura"
},
{
    id: 3,
    name: "Vega"
}
]

const index = [1, 3]

//I want to get a new array like this, making use of both of the arrays above:
filterdList = [
 {
    id: 1,
    name: "Ryu"
 },
 {
    id: 3,
    name: "Vega"
 }   
]

I tried lots of things but I just messed up and was just stack.
How would you accomplish this?
Thank you in advance

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use Array.prototype.filter

const list=[{id:0,name:"Ken"},{id:1,name:"Ryu"},{id:2,name:"Sakura"},{id:3,name:"Vega"},];

const index = [1, 3];

const filteredList = list.filter(({id}) => index.includes(id))

console.log(filteredList);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading