[英]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. 请记住,数组的
indexOf
不适用于IE8及更低版本,必须进行模拟。 I'm also assuming that array1
doesn't contain duplicates. 我还假设
array1
不包含重复项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.