Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

115
Views
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].

//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.

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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

about 4 years ago · Santiago Trujillo Report

0

You can compare two array in for loop like below.

const array1 = [
      { id: "1111", name: "a1" },
      { id: "2222", name: "a2" },
      { id: "3333", name: "a3" },
      { id: "4444", name: "a4" },
      { id: "5555", name: "a5" },
    ];
    
    //child array
    const sub = [{ id: "1111" }, { id: "2222" }];
    
    const indexes = [];
    
    for (let i = 0; i <= sub.length - 1; i++) {
        const subID = sub[i].id;
      for (let j = 0; j <= array1.length - 1; j++) {
          const parentID = array1[j].id;
    
          if(parentID === subID){
              indexes.push(j)
          }
      }
    }
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!