Home > Software engineering >  Find index of array of objects inside another array
Find index of array of objects inside another array

Time:12-26

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.

CodePudding user response:

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

CodePudding user response:

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)
          }
      }
    }
  • Related