假设我们有两个这样的对象数组-
const arr1 = [{id:'1',name:'A'},{id:'2',name:'B'},{id:'3',name:'C'},{id:'4',name:'D'}]; const arr2 = [{id:'1',name:'A',state:'healthy'},{id:'3',name:'C',state:'healthy'}];
我们需要编写一个接受两个这样的数组的JavaScript函数。我们的函数应返回第一个数组的新过滤版本(在此例中为arr1),该版本仅包含那些具有name属性的对象,而这些对象不包含在第二个数组(在此例中为arr2)且具有相同的name属性。
因此,在这种情况下,输出应类似于-
const output = [{id:'2',name:'B'},{id:'4',name:'D'}];
为此的代码将是-
const arr1 = [{id:'1',name:'A'},{id:'2',name:'B'},{id:'3',name:'C'},{id:'4',name:'D'}]; const arr2 = [{id:'1',name:'A',state:'healthy'},{id:'3',name:'C',state:'healthy'}]; const filterByReference = (arr1, arr2) => { let res = []; res = arr1.filter(el => { return !arr2.find(element => { return element.id === el.id; }); }); return res; } console.log(filterByReference(arr1, arr2));
输出结果
控制台中的输出将是-
[ { id: '2', name: 'B' }, { id: '4', name: 'D' } ]