[英]Comparing 2 arrays of objects and removing the duplicates javascript
I'm trying to compare 2 array of objects together and remove the duplicates. 我正在尝试将2个对象数组一起比较,并删除重复项。 For example...
例如...
var array1 = [0, 1, 2, 3, 4, 5, 6];
var array2 = [7, 8, 1, 2, 9, 10];
How can I check the array2 for any element of array1 and if true then remove that from array2 to eliminate the duplication. 我如何检查array2中是否有array1的任何元素,如果为true,则将其从array2中删除以消除重复。
The expected result: array 2 = [7, 8, 9, 10]
预期结果:
array 2 = [7, 8, 9, 10]
Any help would be appreciated, thanks 任何帮助,将不胜感激,谢谢
just filter second array. 只是过滤第二个数组。
const array1 = [0, 1, 2, 3, 4, 5, 6];
const array2 = [7, 8, 1, 2, 9, 10];
const newArray = array2.filter(i => !array1.includes(i));
console.log(newArray);
If the array include primitive types you can use indexOf
and array#reduce
如果数组包含基本类型,则可以使用
indexOf
和array#reduce
const array1 = [0, 1, 2, 3, 4, 5, 6] const array2 = [7, 8, 1, 2, 9, 10] var result = array2.filter((num) => { return array1.indexOf(num) === -1; }); console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
In case of an object, you can get the unique values in second array in comparison to first, please use array#reduce
and array#some
. 如果是对象,则与第一个数组相比,您可以在第二个数组中获得唯一值,请使用
array#reduce
和array#some
。
const person1 = [{"name":"a", "id":0},{"name":"A", "id":1},{"name":"B", "id":2},{"name":"C", "id":3},{"name":"D", "id":4},{"name":"E", "id":5},{"name":"F", "id":6}] const person2 = [{"name":"G", "id":7},{"name":"H", "id":8},{"name":"A", "id":1},{"name":"B", "id":2},{"name":"I", "id":9}, {"name":"J", "id":10}] var unique = person2.reduce((unique, o) => { let isFound = person1.some((b) => { return b.id === o.id; }); if(!isFound) unique.push(o); return unique; },[]); console.log(unique);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can use do this: 您可以使用以下方法:
var array1 = [0, 1, 2, 3, 4, 5, 6];
var array2 = [7, 8, 1, 2, 9, 10];
/* run a filter function for every value in array2 and returned the final filtered array */
var array3 = array2.filter(function(currentValue, index, arr){
return (array1.indexOf(currentValue) === -1); /* this will check whether currentValue exists in aray1 or not. */
});
console.log(array3) /* filtered array */
This should deliver what you want. 这应该可以提供您想要的东西。 Or another way:
或另一种方式:
var array1 = [0, 1, 2, 3, 4, 5, 6];
var array2 = [7, 8, 1, 2, 9, 10];
var duplicateRemoved = [];
/* run a function for every value in array2 and collect the unique value in a new array */
array2.forEach(function(currentValue, index, arr){
if (array1.indexOf(currentValue) === -1) {
duplicateRemoved.push(currentValue);
}
});
console.log(duplicateRemoved)
This should work in your situation unless there are some other external factors associated with it. 除非有其他外部因素与之相关,否则这应该可以解决您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.