我必须过滤一个数组并将其与另一个有条件的数组进行比较。
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中可以多次。
答案 0 :(得分:0)
尝试关注。
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; }