2017-09-11 31 views
1

如何比較兩個javascript數組並創建兩個缺失和新元素的新數組?數組元素將始終是字符串或數字,並不能100%確定它們將以任何方式排序。比較兩個數組,並使用純javascript或jquery創建兩個新數組,並使用缺失和新元素

var array1= ['11', '13', '14', '18', '22', '23', '25']; 
var array2= ['11', '13', '15', '16', '17', '23', '25', '31']; 
var missing_elements = []; 
var new_elements = []; 

***Required Output:*** 
missing_elements= ['14', '18', '22'] 
new_elements= ['15', '16', '17', '31'] 
+0

歡迎的StackOverflow! 你到目前爲止嘗試過什麼嗎? StackOverflow不是一個免費的代碼寫入服務,並且期待你 [嘗試先解決你自己的問題](http://meta.stackoverflow.com/questions/261592)。 請更新您的問題,以顯示您已經嘗試過的內容,顯示您在 [最小,完整和可驗證示例](http://stackoverflow.com/help/mcve)中遇到的具體問題。 欲瞭解更多信息,請參閱 [如何問一個好問題], 並採取 [網站之旅](http:// http:// stackoverflow.com/tour) –

回答

1

那麼一個簡單的解決方案只是遍歷array1,與.includes()測試在同一時間的元素之一,產生缺失的元素的列表,然後反向做,以獲得新的元素列表。

你可以使用.filter()arrow functions儘量簡短:

var array1= ['11', '13', '14', '18', '22', '23', '25']; 
 
var array2= ['11', '13', '15', '16', '17', '23', '25', '31']; 
 

 
var missing_elements = array1.filter(v => !array2.includes(v)); 
 
var new_elements = array2.filter(v => !array1.includes(v)); 
 

 
console.log(missing_elements); 
 
console.log(new_elements);

+0

效果很好。但是,如果array2有重複值,那麼如何刪除重複值?例如:var array2 = ['11','13','15','16','17','23','25','31','17','11']; – Divya

+0

從其他問題中刪除數組中的重複項,其中包括[此優秀答案](https://stackoverflow.com/a/9229821/615754)。你可以將其中的一種技術與我所展示的技術結合起來,或者在之前或之後做一個單獨的'.filter()'。 – nnnnnn

相關問題