2016-04-15 68 views
0

我有一個數組對象如下:一個陣列中刪除重複對象

細節:

Array[2] 
>0: Object 
    Name:"a" 
    Desc:"Desc" 
>1: Object 
    Name:"b" 
    Desc:"Desc2" 
>2: Object 
    Name:"C" 
    Desc:"Desc" 

我想刪除自「商品說明」的最後一個對象具有與第一條目的重複條目。

我試圖在JavaScript這種方法,

removedup = details.reduce(function(a,b) { if (a.indexOf(b) < 0) a.push(b); return a },[]); 

我想要的輸出,以便移除重複並因此調整數組的大小。

細節:

Array[1] 
>0: Object 
    Name:"a" 
    Desc:"Desc" 
>1: Object 
    Name:"b" 
    Desc:"Desc2" 

我能在邏輯上修改?

+0

[將動態ArrayList與ArrayList進行比較!並刪除動態數組中不存在的元素](http://stackoverflow.com/questions/31378088/compare-a-dynamic-arraylist-with-arraylist-and-remove-the-elements-which-are-no ) – Praneeth

+0

可能的重複[刪除數組中的重複對象](http://stackoverflow.com/questions/2218999/remove-duplicates-from-an-array-of-objects-in-javascript) – kiro112

回答

3

你可以使用Array#filter()thisArgs的臨時對象。 。

var details = [{ Name: 'a', desc: 'Desc' }, { Name: 'b', desc: 'Desc2' }, { Name: 'C', desc: 'Desc' }, {Name: 'a', desc: 'toString'}], 
 
    removedup = details.filter(function (a) { 
 
     if (!(a.desc in this)) { 
 
      this[a.desc] = true; 
 
      return true; 
 
     } 
 
    }, Object.create(null)); 
 

 
document.write('<pre> ' + JSON.stringify(removedup, 0, 4) + '</pre>');

+2

「{Name:' a',desc:'toString'}'? – georg

+0

僅供參考你的樣品中沒有重複... – Seabizkit

+0

@georg,它應該發生什麼? –

1

試試這個:

var modified = details.filter(function (item) { 
    return !details.some(function (item_) { 
     return item_ !== item && item_.Desc === item.Desc; 
    }); 
}); 
0

使用loadash

VAR輸出= _.chain(陣列).reverse()indexBy( '​​商品說明')的toArray()值();