我有两个数组
var a= $("#update-select1").val(); // gives value 1,2,4
var b= $("#update-select2").val(); // 1,2,5
我想要与上述两个数组不同的两个数组。
//array has the values which is in `b` but not in `a`
var c = [5]
//another array has value in `a` but not in `b`
var d =[4]
最佳答案
您可以这样使用Array.filter
:
var c = [1,2,5]
.filter(function(a){return this.indexOf(a) === -1},[1,2,4]); //=> [5]
var d = [1,2,4]
.filter(function(a){return this.indexOf(a) === -1},[1,2,5]); //=> [4]
或者:
function notIn(a){
return this.indexOf(a) === -1;
}
var a = [1,2,4]
,b = [1,2,5]
,c = b.filter(notIn,a)
,d = a.filter(notIn,b);
关于Javascript/Jquery-现有两个数组的新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20856697/