首页 > 解决方案 > 比较两个数组并找出差异

问题描述

所以,基本上我有两个这样的数组

   const firstArray = [
     {
        subId:40,
        value:280,
        label:'something'
     
     },
{
        subId:42,
        value:280,
        label:'something different'
     
     }
    ]

和另一个包含视频的数组

const secondary = [
{
    chapId: 280,
    label:'any video',
    
},
{
    chapId: 280,
    label:'another video',      
},
{
    chapId: 282,
    label:'another video',      
}
]

现在我想返回在 firstArray firstArray.value === secondary.chapId 中匹配的辅助数组中的所有结果。

结果如下:

 const secondary = [
    {
        chapId: 280,
        label:'any video',
        
    },
    {
        chapId: 280,
        label:'another video',      
    },
    
    ]

我用 reduce 试过了,但我没有得到确切的值

我想将下拉列表中的结果数组用于反应组件。

标签: javascriptreactjs

解决方案


尝试一下。

const firstArray = [
  {
 subId:40,
 value:280,
 label:'something'
  
  },
{
 subId:42,
 value:280,
 label:'something different'
  
  }
 ]

const secondary = [
  {
  chapId: 280,
  label:'any video',
  
  },
  {
  chapId: 280,
  label:'another video',      
  },
  {
  chapId: 282,
  label:'another video',      
  }
  ]

let ret = secondary.filter((x) => firstArray.find((y) => x.chapId === y.value));
console.log(ret);


推荐阅读