Javascript/Jquery-现有两个数组的新数组

标签 javascript jquery

我有两个数组

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

See also

关于Javascript/Jquery-现有两个数组的新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20856697/

相关文章:

javascript - 如何监控javascript改变的HTML输入值

javascript - 使用 jquery 动态添加字幕内容

javascript - 停止书写后输入文本后触发 Action ?

javascript - 用 f 替换 js 函数关键字

javascript 或 css - 几乎可以工作,遇到一些障碍

javascript - 如何从 html Canvas 上的tileset工作表多次绘制特定的tileset而不是整个图像

javascript - 如何对动态呈现的表格进行排序?

javascript - 网页从MySQL加载图片慢

php - 如何在通过 Ajax 提交的表单上重新加载验证码?

jquery - 使用 Google map 标记绑定(bind) jQuery 元素点击