简体   繁体   中英

Find the index of element in an array against another array

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 )

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]

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

You can use this implement:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM