我有兩個數組與對象,如arr1和arr2,我想分開重複的項目和原始項目。我的意思是,從arr1開始,無論項目是否與arr2匹配,那麼這些項目[來自arr1]都被視爲重複項目。如果它不匹配,那麼它就是原始物品。如何比較兩個對象數組中的重複javascript
我做了以下程序,但它很未按預期
arr1 = [{name: "sunrise.jpg"},{name: "nature.jpg"},{name:"sunflower.jpg"}, {name: "sunset.jpg"}];
arr2 = [{
"@type" : "Image",
"objectTypeId" : "Image",
"baseTypeId" : "document",
"name" : "sunrise.jpg",
"width" : "284",
"height" : "177"
}, {
"@type" : "Image",
"objectTypeId" : "Image",
"baseTypeId" : "document",
"name" : "Lao Tzu",
"width" : "638",
"height" : "960"
}, {
"@type" : "Image",
"objectTypeId" : "Image",
"baseTypeId" : "document",
"name" : "nature.jpg",
"width" : "300",
"height" : "168"
}, {
"@type" : "Image",
"objectTypeId" : "Image",
"baseTypeId" : "document",
"name" : "replay_12",
"width" : "500",
"height" : "717"
}, {
"@type" : "Image",
"objectTypeId" : "Image",
"baseTypeId" : "document",
"name" : "sunflower.jpg",
"width" : "300",
"height" : "168"
}
];
var originalItems = [];
var diff = function(arr1, arr2) {
var dupes = [];
for(var i in arr1) {
//console.log(i);
for(var j in arr2){
if(arr1[i].name === arr2[j].name){
dupes.push(arr2[j]);
} else {
originalItems.push(arr2[j]);
}
}
}
return dupes;
}
var sd = diff(arr1, arr2);
console.log(sd);
console.log(originalItems);
在這裏,原來的項目有「sunset.jpg」和其他被移動到「愚弄」。
我錯過了這裏的任何線索,請問?
你有什麼期望從上面的例子的結果? –
我堅持複製和粘貼你的代碼在jsfiddle中,結果不是你說的。我得到愚蠢=日出,自然,向日葵;其餘的在原件。我什麼也沒做,只是複製並粘貼 – lascort
@Kinduser實際上,你是對的,它不工作,「originalItems」數組包含所有項目。但結果絕對不是問題所在。但是,是的,我的壞 – lascort