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

Find index of array of objects inside another array

I have 2 array of objects with as shown below.    
I want to find the index by searching the child array 'sub' in parent array 'array1' keeping id as the key.

I want to search sub array in array1 and find the index of values like [0,1,2,3].

Hence my expected output should be [0,1,2,3].    
Please help me out on this.



//parent array    
 array1 = [
    { "id": "1111", "name": "a1"},
    { "id": "2222", "name": "a2" },
    { "id": "3333", "name": "a3" },
    { "id": "4444", "name": "a4" },
    {"id": "5555", "name": "a5" },
];


//child array
 sub = [
    { "id": "1111"},
    { "id": "2222" }        
];

I’m struggling with find the child array on the parent array
as it includes the array of objects with key values.

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 could use a Set for all id of sub and then filter the indices for seen id of array1.

const
    array1 = [{ id: "1111", name: "a1" }, { id: "2222", name: "a2" }, { id: "3333", name: "a3" }, { id: "4444", name: "a4" }, { id: "5555", name: "a5" }],
    sub = [{ id: "1111" }, { id: "2222" }],
    subIds = new Set(sub.map(({ id }) => id)),
    result = [...array1.keys()].filter(i => subIds.has(array1[i].id));

console.log(result);
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