2013-07-24 57 views
7

我需要做的就是比較兩個對象數組,並刪除第二個具有相同屬性值的項目。例如:比較兩個對象數組並刪除第二個具有相同屬性值的項目

var a = [{'name':'bob', 'age':22}, {'name':'alice', 'age':12}, {'name':'mike', 'age':13}]; 
var b = [{'name':'bob', 'age':62}, {'name':'kevin', 'age':32}, {'name':'alice', 'age':32}]; 

function remove_duplicates(a, b) { 
    for (var i = 0, len = a.length; i < len; i++) { 
     for (var j = 0, len = b.length; j < len; j++) { 
      if (a[i].name == b[j].name) { 
       b.splice(j, 1); 
      } 
     } 
    } 

    console.log(a); 
    console.log(b); 

} 

console.log(a); 
console.log(b); 

remove_duplicates(a,b); 

我不明白爲什麼這不工作,而是給出了:

Uncaught TypeError: Cannot read property 'name' of undefined 

我期待什麼是B中的以下內容:

[{'name':'kevin', 'age':32}]; 
+0

也許因爲在你的循環中重新定義了'len'變量 –

回答

10

FIDDLE

for (var i = 0, len = a.length; i < len; i++) { 
     for (var j = 0, len2 = b.length; j < len2; j++) { 
      if (a[i].name === b[j].name) { 
       b.splice(j, 1); 
       len2=b.length; 
      } 
     } 
    } 
1

試試這個:

您從0開始循環。

for (var i = 0, len = a.length; i < len; i++) { 
     for (var j = 0, len = b.length; j < len-1; j++) { 
      if (a[i].name == b[j].name) { 
       b.splice(j, 1); 
      } 
     } 
    } 

Fiddle Demo

1

你的問題是,splice()將改變數組的長度,讓你預先計算len值會過大和內環路您嘗試訪問未定義的元素。

一種可能的解決辦法是使用filter()方法:

function remove_duplicates(a, b) { 

    b = b.filter(function(item) { 
     for(var i=0, len=a.length; i<len; i++){ 
      if(a[i].name == item.name) { 
       return false; 
      } 
     } 
     return true; 
    }); 

    console.log(a); 
    console.log(b); 
} 

Example Fiddle

+0

這也將解決內部和外部for循環中相同'len'的問題。 – Andreas

0

的根本原因是,你直接拼接從數組b而項你在for循環中,並且前提條件是a和b具有相同的數字o f項目。

3

你只需要休息找到匹配的內循環:

if (a[i].name == b[j].name) { 
    b.splice(j, 1); 
    break; 
} 
0

比較和對象數據類型的數組object.Typically的數組中刪除可能TYPEOF是object.So我們需要轉換成JSON字符串化,然後檢查條件..

for(var i=0; i < a.length; i++) { 
 
        for(var j=0; j < b.length; j++) { 
 
         if(JSON.stringify(a[i]) == JSON.stringify(b[j])) { 
 
          a.splice(i, 1); 
 
         } 
 
        } 
 
       }

相關問題