如何在Javascript中获取两个数组之间的差异?

如何在Javascript中获取两个数组之间的差异?

有没有办法在JavaScript中返回两个数组之间的差异?

例如:

var a1 = ['a', 'b'];var a2 = ['a', 'b', 'c', 'd'];// need ["c", "d"]

任何建议都非常感谢。


慕森王
浏览 1714回答 3
3回答

弑天下

我假设你正在比较一个普通的数组。如果没有,则需要将for循环更改为for ... in循环。function arr_diff (a1, a2) {&nbsp; &nbsp; var a = [], diff = [];&nbsp; &nbsp; for (var i = 0; i < a1.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; a[a1[i]] = true;&nbsp; &nbsp; }&nbsp; &nbsp; for (var i = 0; i < a2.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; if (a[a2[i]]) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; delete a[a2[i]];&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; a[a2[i]] = true;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; for (var k in a) {&nbsp; &nbsp; &nbsp; &nbsp; diff.push(k);&nbsp; &nbsp; }&nbsp; &nbsp; return diff;}console.log(arr_diff(['a', 'b'], ['a', 'b', 'c', 'd']));console.log(arr_diff("abcd", "abcde"));console.log(arr_diff("zxc", "zxc"));如果您不关心向后兼容性,更好的解决方案是使用过滤器。但是,这个解决方案仍然有效。

交互式爱情

Array.prototype.diff = function(a) {&nbsp; &nbsp; return this.filter(function(i) {return a.indexOf(i) < 0;});};////////////////////&nbsp;&nbsp;// Examples&nbsp;&nbsp;////////////////////[1,2,3,4,5,6].diff( [3,4,5] );&nbsp;&nbsp;// => [1, 2, 6]["test1", "test2","test3","test4","test5","test6"].diff(["test1","test2","test3","test4"]);&nbsp;&nbsp;// => ["test5", "test6"]Array.prototype.diff = function(a) {&nbsp; &nbsp; return this.filter(function(i) {return a.indexOf(i) < 0;});};////////////////////&nbsp;&nbsp;// Examples&nbsp;&nbsp;////////////////////var dif1 = [1,2,3,4,5,6].diff( [3,4,5] );&nbsp;&nbsp;console.log(dif1); // => [1, 2, 6]var dif2 = ["test1", "test2","test3","test4","test5","test6"].diff(["test1","test2","test3","test4"]);&nbsp;&nbsp;console.log(dif2); // => ["test5", "test6"]注意&nbsp;indexOf和filter在ie9之前不可用。

12345678_0001

到目前为止,这是使用jQuery获得您正在寻找的结果的最简单方法:var&nbsp;diff&nbsp;=&nbsp;$(old_array).not(new_array).get();diff现在包含了old_array不存在的内容new_array
打开App,查看更多内容
随时随地看视频慕课网APP