检查javascript中两个对象数组之间的区别

时间:2018-06-01 17:03:09

标签: javascript arrays

我需要一些帮助。如何在这种情况下得到差异的数组:

var b1 = [
  { id: 0, name: 'john' }, 
  { id: 1, name: 'mary' }, 
  { id: 2, name: 'pablo' }, 
  { id: 3, name: 'escobar' } 
]; 

var b2 = [
  { id: 0, name: 'john' }, 
  { id: 1, name: 'mary' }
];

我想要一系列差异:

// [{ id: 2, name: 'pablo' }, { id: 3, name: 'escobar' }]

最优化的方法是怎样的?

我正在尝试过滤一个缩小的数组..这一行:

var Bfiltered = b1.filter(function (x) {
return x.name !== b2.reduce(function (acc, document, index) {
    return (document.name === x.name) ? document.name : false
},0)

});

console.log("Bfiltered", Bfiltered);
// returns { id: 0, name: 'john' }, { id: 2, name: 'pablo' }, { id: 3, name: 'escobar' } ]

谢谢,

机器人

3 个答案:

答案 0 :(得分:3)

.Filter().some()函数可以解决问题



var b1 = [
  { id: 0, name: 'john' }, 
  { id: 1, name: 'mary' }, 
  { id: 2, name: 'pablo' }, 
  { id: 3, name: 'escobar' } 
]; 

var b2 = [
  { id: 0, name: 'john' }, 
  { id: 1, name: 'mary' }
];

var res = b1.filter(item1 => 
!b2.some(item2 => (item2.id === item1.id && item2.name === item1.name)))

console.log(res);




答案 1 :(得分:1)

您可以使用filter过滤/循环数组,some检查数组2上是否存在ID



var b1 = [{ id: 0, name: 'john' }, { id: 1, name: 'mary' }, { id: 2, name: 'pablo' }, { id: 3, name: 'escobar' } ]; 
var b2 = [{ id: 0, name: 'john' }, { id: 1, name: 'mary' }];

var result = b1.filter(o => !b2.some(v => v.id === o.id));

console.log(result);




如果数组1更长,上面的示例将起作用。如果你不知道哪一个更长,你可以使用sort来排列数组并使用reducefilter



var b1 = [{ id: 0, name: 'john' }, { id: 1, name: 'mary' }, { id: 2, name: 'pablo' }, { id: 3, name: 'escobar' } ]; 
var b2 = [{ id: 0, name: 'john' }, { id: 1, name: 'mary' }];

var result = [b1, b2].sort((a,b)=> b.length - a.length)
                     .reduce((a,b)=>a.filter(o => !b.some(v => v.id === o.id)));

console.log(result);




答案 2 :(得分:0)

另一种可能性是使用Map,如果处理Map,则可以将时间复杂度降低到 O(max(n,m))结果对您来说很好:

function findArrayDifferences(arr1, arr2) {
const map = new Map();
const maxLength = Math.max(arr1.length, arr2.length);
for (let i = 0; i < maxLength; i++) {
	if (i < arr1.length) {
		const entry = arr1[i];
		if (map.has(entry.id)) {
			map.delete(entry.id);
		} else {
			map.set(entry.id, entry);
		}

	}
	if (i < arr2.length) {
		const entry = arr2[i];
		if (map.has(entry.id)) {
			map.delete(entry.id);
		} else {
			map.set(entry.id, entry);
		}

	}
}
return map;
}

const arr1 = [{id:0,name:'john'},{id:1,name:'mary'},{id:2,name:'pablo'},{id:3,name:'escobar'}];
const arr2 = [{id:0,name:'john'},{id:1,name:'mary'},{id:99,name:'someone else'}];
const resultAsArray = [...findArrayDifferences(arr1,arr2).values()];
console.log(resultAsArray);