![](/img/trans.png)
[英]Comparing two JavaScript Arrays of Objects and removing common Array Objects
[英]Comparing 2 arrays of objects and removing the duplicates javascript
我正在嘗試將2個對象數組一起比較,並刪除重復項。 例如...
var array1 = [0, 1, 2, 3, 4, 5, 6];
var array2 = [7, 8, 1, 2, 9, 10];
我如何檢查array2中是否有array1的任何元素,如果為true,則將其從array2中刪除以消除重復。
預期結果: array 2 = [7, 8, 9, 10]
任何幫助,將不勝感激,謝謝
只是過濾第二個數組。
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);
如果數組包含基本類型,則可以使用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; }
如果是對象,則與第一個數組相比,您可以在第二個數組中獲得唯一值,請使用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; }
您可以使用以下方法:
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 */
這應該可以提供您想要的東西。 或另一種方式:
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)
除非有其他外部因素與之相關,否則這應該可以解決您的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.