Home > front end >  Getting sub index of the parent collection
Getting sub index of the parent collection

Time:11-23

i have an parent array of objects

const parent = [{name: 'one', id: 1}, {name: 'two', id: 2}, {name: 'three', id: 3}, {name: 'four', id: 4}, {name: 'five', id: 5}]

i have made sub arrays out of it

const childrenCollection  = [[{name: 'one', id: 1}, {name: 'two', id: 2}], [{name: 'three', id: 3}, {name: 'four', id: 4}], [{name: 'five', id: 5}]]

now i am looping through the childrenCollection

childrenCollection.map(childrenSubCollection => {
  // find the actual index from the main parent array
  const indexOfOne = childrenSubCollection.findIndex(childrenSub => {
    return childrenSub[0].id === // ??
  })

   const indexOfTwo = childrenSubCollection.findIndex(childrenSub => {
    return childrenSub[1].id === // ??
  })

  console.log(childrenSubCollection[0], childrenSubCollection[1], 'index',  indexOfOne, indexOfTwo )
})

How can i find the index of each from parent array

CodePudding user response:

  • Using Array#findIndex:

const 
  parent = [ { name: 'one', id: 1 }, { name: 'two', id: 2 }, { name: 'three', id: 3 }, { name: 'four', id: 4 }, { name: 'five', id: 5 } ],
  childrenCollection  = [
    [ { name: 'one', id: 1 }, { name: 'two', id: 2 } ], 
    [ { name: 'three', id: 3 }, { name: 'four', id: 4 } ], 
    [ { name: 'five', id: 5 } ]
  ];

childrenCollection.forEach(([ one, two ]) => {
  const indexOfOne = one ? parent.findIndex(item => one.id === item.id) : -1;
  const indexOfTwo = two ? parent.findIndex(item => two.id === item.id) : -1;
  console.log(one, two, 'index', indexOfOne, indexOfTwo);
});

  • Using Map:

const 
  parent = [ { name: 'one', id: 1 }, { name: 'two', id: 2 }, { name: 'three', id: 3 }, { name: 'four', id: 4 }, { name: 'five', id: 5 } ],
  childrenCollection  = [
    [ { name: 'one', id: 1 }, { name: 'two', id: 2 } ], 
    [ { name: 'three', id: 3 }, { name: 'four', id: 4 } ], 
    [ { name: 'five', id: 5 } ]
  ];

const indexMap = new Map( parent.map(({ id }, index) => ([ id, index ])) );
childrenCollection.forEach(([ one, two ]) => {
  const indexOfOne = one ? indexMap.get(one.id) : -1;
  const indexOfTwo = two ? indexMap.get(two.id) : -1;
  console.log(one, two, 'index', indexOfOne, indexOfTwo);
});

  • Related