2016-12-02 46 views
-2

我在我的angular 2 .ts(type script)文件中聲明瞭如下所示的兩個數組。如何在JS或Angualr中有效地比較數組2

parentArray:Array<Model> and initialized with {a,b,c,d} 
modifiedAarray:Array<Model> modified with data {c,e,f,g} 

通過比較兩個數組如何有效地找到兩者之間的區別? [ie]查找新增和已有元素

+0

環路他們使用的indexOf,看它是否在其他存在 –

回答

0

使用filter

var original = ['a','b','c','d']; 
 
var newarray = ['c','e','f','g']; 
 

 
var addedEls = newarray.filter(function(a){ return original.indexOf(a) < 0; }); 
 
var remvdEls = original.filter(function(a){ return newarray.indexOf(a) < 0; }); 
 

 
alert("These were added: "+addedEls.join(",")); 
 
alert("These were removed: "+remvdEls.join(","));

0

使用filterObservable

Observable.from(parentArray) 
    .filter(item => { 
    // Condition here with modifiedAarray 
    // IE: return modified.attribute !== item.attribute; 
    }) 
    .subscribe(item => console.log(item));