比较两个数组并过滤条件

时间:2019-05-14 06:34:16

标签: 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', 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具有该对象一次,或者,如果类型为multi,则它在array2中可以多次。

2 个答案:

答案 0 :(得分:0)

尝试关注。

  • 为array2转换一个映射,其中key为id,value为它的出现
  • 根据以下规则过滤array1
    • 如果类型为多个,则它应该在地图中存在且出现不止一次
    • 如果类型是单一类型,则它根本不应该存在于地图中。

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',type:'drafted'}];

let a2Map = array2.reduce((a,c) => {
  a[c.newId] = a[c.newId] || 0;
  a[c.newId]++;
  return a;
}, {});

let result = array1.filter(v => v.type === 'multiple' ? a2Map[v.id] > 1 : !a2Map.hasOwnProperty(v.id));

console.log(result);

答案 1 :(得分:0)

您可以取Map并计算newId中具有相同array2的所有项目。然后使用单个或多个值的条件过滤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: 'q2', status: 'submitted' }, { newId: 'q4', type: 'drafted' }],
    map = array2.reduce((m, { newId }) => m.set(newId, (m.get(newId) || 0) + 1), new Map),
    result = array1.filter(({ id, type }) =>
        type === 'single' && !map.get(id) || // not in map, count:  0
        type === 'multiple' && map.get(id)   // in map,     count: >0    
    );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

相关问题