比较2阵列返回区别 [英] Compare 2 arrays which returns difference
问题描述
什么是比较两个数组,并返回区别最快/最好的方法是什么?就像和array_diff
在PHP。有一个简单的功能,还是我将不得不通过创建各一个()
?或的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 {您可以搜索或阅读的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.
到底警报提示罕见的元素数组的数组,即相差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!
code
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
这篇关于比较2阵列返回区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!