比较两个返回差异的数组 [英] Compare 2 arrays which returns difference
问题描述
比较两个数组并返回差异的最快/最佳方法是什么?很像 PHP 中的 array_diff
.是否有一个简单的函数,或者我必须通过 each()
创建一个函数?还是 foreach
循环?
What's the fastest/best way to compare two arrays and return the difference? Much like array_diff
in PHP. Is there an easy function or am I going to have to create one via each()
? or a foreach
loop?
推荐答案
工作演示 http://jsfiddle.net/u9xES/
好的链接(Jquery 文档):http://docs.jquery.com/Main_Page {you可以在这里搜索或阅读 API}
Good link (Jquery Documentation): http://docs.jquery.com/Main_Page {you can search or read APIs here}
如果您希望在 JQuery 中进行此操作,希望这对您有所帮助.
Hope this will help you if you are looking to do it in JQuery.
最后的alert提示不常见元素Array的数组,即2个数组的区别.
The alert in the end prompts the array of uncommon element Array i.e. difference between 2 array.
如果我错过了什么,请让我知道,干杯!
Please lemme know if I missed anything, cheers!
代码
var array1 = [1, 2, 3, 4, 5, 6];
var array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var difference = [];
jQuery.grep(array2, function(el) {
if (jQuery.inArray(el, array1) == -1) difference.push(el);
});
alert(" the difference is " + difference); // Changed variable name
这篇关于比较两个返回差异的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!