问题描述
如何比较数组中的对象,并输出字段值与其他对象不匹配的对象(忽略id字段)。用Javascript,ES6或Lodash怎么做?
您应该了解的事情:输入数组应为任意长度,对象可以具有其他字段,但在比较时会被忽略。应该输出奇数对象,或者如果没有多数,则输出所有对象。
const array1 = [{_id:'1',cow: true,sheep: true,pig: false},{_id:'2',cow: false,pig: true},{_id:'3',pig: false}]
const array2 = [{_id:'1',pig: false}]
// expected array1 outcome:
{_id:'2',pig: true}
// expected array2 outcome:
[{_id:'1',pig: false}]
解决方法
function diff(array) {
const m = new Map();
for (const {cow,sheep,pig} of array) {
const str = `${cow}${sheep}${pig}`;
m.set(str,(m.get(str) || 0) + 1);
}
const result = [];
for (let i = 0; i < array.length; i++) {
const {cow,pig} = array[i];
const str = `${cow}${sheep}${pig}`;
if (m.get(str) == 1) {
result.push(array[i])
}
}
if (result.length) {
return result;
}
return array;
}