简体   繁体   English

根据另一个数组查找数组中元素的索引

[英]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 )如何检查在IDS arrayTwo针对IDS arrayOne并返回类似ID出现的结果指标像现在这样[1, 3]基于arrayOne我们可以在索引1和索引3有发生在IDS看到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)
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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