简体   繁体   中英

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

I have two arrays:

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

I need to have a function that returns an array of the items not in the second Array.

var notInSecond = [c,d];

Does anyone know how to do this?

Thanks.

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);
}

Keep in mind that indexOf for arrays isn't available for IE8 and lower and it must be emulated. I'm also assuming that array1 doesn't contain duplicates.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM