Home > Enterprise >  Find the index of element in an array against another array
Find the index of element in an array against another array

Time:11-05

Say I have two arrays of objects

arrayOne = [{revision: { id: 1 }}, {revision: { id: 2 }}, {revision: { id: 3 }}, {revision: { id: 4 }}]

arrayTwo = [{someOtherProp: { id: 2 }}, {someOtherProp: { id: 4 }}]

How do I check the ids in arrayTwo against ids in arrayOne and returns the result index of the similar id occurrences like so [1, 3] (based on arrayOne we can see on index 1 and index 3 have ids that occur in arrayTwo)

CodePudding user response:

This should work

arrayOne = [{revision: { id: 1 }}, {revision: { id: 2 }}, {revision: { id: 3 }}, {revision: { id: 4 }},{revision: { id: 5 }}];

arrayTwo = [{someOtherProp: { id: 2 }}, {someOtherProp: { id: 4 }}];

console.log(arrayOne.filter(o1 => arrayTwo.some(o2 => o1.revision.id === o2.someOtherProp.id)).map(x => arrayOne.findIndex(y => y.revision.id === x.revision.id))); // [1, 3]

CodePudding user response:

This should work for your case:

one = [{revision: { id: 1 }}, {revision: { id: 2 }}, {revision: { id: 3 }}, {revision: { id: 4 }}]

two = [{someOtherProp: { id: 2 }}, {someOtherProp: { id: 4 }}]

for(let i in two) {
  for(let j in one) {
    if(two[i]['someOtherProp']['id']==one[j]['revision']['id']){
      console.log(i,j)
    }
  }
}

CodePudding user response:

You can use this implement:

arrayTwo.map(v=>{return v['someOtherProp']['id']}).map(v=>{
    return arrayOne.map(v=>{return v['revision']['id']}).indexOf(v)
})
  • Related