簡體   English   中英

Javascript比較兩個不同大小的數組,並返回不在第二個數組中的項目

[英]Javascript Compare two arrays with different sizes and return the items that are not in second array

我有兩個數組:

var array1 = [a,b,c,d];
var array2 = [1,2,a,b];

我需要一個函數返回不在第二個數組中的項目數組。

var notInSecond = [c,d];

有誰知道如何做到這一點?

謝謝。

var notInSecond = array1.slice(0); // Creates a clone of array1
for (var i = 0, j; i < array2.length; i++) {
    j = notInSecond.indexOf(array2[i]);
    if (j > -1) notInSecond.splice(j, 1);
}

請記住,數組的indexOf不適用於IE8及更低版本,必須進行模擬。 我還假設array1不包含重復項。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM