Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 比较两个数组并根据条件筛选_Javascript_Arrays - Fatal编程技术网

Javascript 比较两个数组并根据条件筛选

Javascript 比较两个数组并根据条件筛选,javascript,arrays,Javascript,Arrays,我必须过滤一个数组,并将其与另一个具有条件的数组进行比较 const array1 = [ {id: 'q1', type: 'single'}, {id: 'q2', type: 'multiple'}, {id: 'q3', type: 'single'}, {id: 'q4', type: 'single'} ]; const array2 = [ {newId: 'q1', status: 'submitted'}, {newId: 'q2'

我必须过滤一个数组,并将其与另一个具有条件的数组进行比较

const array1 = [
    {id: 'q1', type: 'single'},
    {id: 'q2', type: 'multiple'},
    {id: 'q3', type: 'single'},
    {id: 'q4', type: 'single'}
];

const array2 = [
   {newId: 'q1', status: 'submitted'},
   {newId: 'q2', status: 'drafted'},
   {newId: 'q2', status: 'submitted'},
   {newId: 'q2', status: 'submitted'},
   {newId: 'q4', status: 'drafted'}
];
const resultArray = [
   {id: 'q2', type: 'multiple'}, 
   {id: 'q3', type: 'single'}
];
我尝试了map函数,但得到了错误的结果。这是我的代码:

let resultArray = [];
map(array1, el => {
    if(el.type==='single'){
        map(array2, elm => {
            if(el.id!==elm.newId){
                newData.push(el);
            }
        })
    }else{
        newData.push(el);
    }
});
newData = uniqBy(newData, 'id');
array1的类型为single/multiple,如果该类型为single,则array2有一次该对象;如果该类型为multiple,则可以在array2中多次使用该对象。

请尝试以下操作

  • 转换array2的映射,其中键为id,值为其引用
  • 根据以下规则筛选阵列1
    • 若类型是多个,那个么它应该在映射中多次出现
    • 否则,若类型是单一的,那个么它就不应该存在于映射中
const array1=[{id:'q1',type:'single'},{id:'q2',type:'multiple'},{id:'q3',type:'single'},{id:'q4',type:'single'}];
const array2=[{newId:'q1',状态:'submitted'},{newId:'q2',状态:'drafted'},{newId:'q2',状态:'submitted'},{newId:'q4',类型:'drafted'}];
设a2Map=array2.reduce((a,c)=>{
a[c.newId]=a[c.newId]| | 0;
a[c.newId]++;
返回a;
}, {});
让result=array1.filter(v=>v.type=='multiple'?a2Map[v.id]>1:!a2Map.hasOwnProperty(v.id));

控制台日志(结果)
您可以使用
地图
并从
array2
中计算具有相同
newId
的所有项目。然后使用单个或多个值的条件过滤
Array2

const
array1=[{id:'q1',type:'single'},{id:'q2',type:'multiple'},{id:'q3',type:'single'},{id:'q4',type:'single'}],
array2=[{newId:'q1',status:'submitted'},{newId:'q2',status:'drafted'},{newId:'q2',status:'submitted'},{newId:'q4',type:'drafted'},
map=array2.reduce((m,{newId})=>m.set(newId,(m.get(newId)| | 0)+1),newmap),
result=array1.filter({id,type})=>
type=='single'&&!map.get(id)| |//不在映射中,计数:0
type=='multiple'&&map.get(id)//在映射中,计数:>0
);
控制台日志(结果)

.as控制台包装{最大高度:100%!重要;顶部:0;}
比较条件是什么?预期输出是什么?如何将
q3
过滤入和
q1
q4
过滤出?这背后的过滤逻辑是什么?@RaviKumarGopalakrishnan您说的
如果类型是单阵列2,则将该对象一次过滤掉
,那么在array2中,
q3
在哪里发生过一次?@RaviKumarGopalakrishnan-很高兴能帮助你!