如何仅在jquery中的2个数组之间找到公共元素 [英] How to find common elements only between 2 arrays in jquery
问题描述
var array1 = [1, 2, 3, 4, 5, 6];
var array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9];
我有两个像上面一样的数组.现在我想使用 jQuery 在 MVC 4 中执行以下操作.
I have two arrays like above. Now I want to do the following in MVC 4 with jQuery.
如果两个数组的每个元素都相等,则显示消息/警报.例如所有记录已经存在."
If every elements of both arrays are equal then show a message/alert. e.g. "All records already existing."
如果两个数组的每个元素都不同,则只需将它们全部添加到VAR"中,例如var resultset = ....
(其中 7,8,9 将存储)
If every elements of both the arrays are different then just add them all in a "VAR", e.g. var resultset = ....
(where 7,8,9 will stored)
如果两个数组之间的公共元素很少,那么对于公共元素,会显示带有元素的消息,例如记录 1、2、3、4、5、6 已经存在"并在VAR"中添加不同的元素,例如var resultset = ....
(其中 7,8,9 将存储).消息和差异元素集合将同时执行.
If few elements common between two arrays then for the common elements show a message with element, e.g. "Record 1,2,3,4,5,6 are already exists" and add the different elements in "VAR", e.g. var resultset = ....
(where 7,8,9 will stored). Both the message and difference elements collection will perform at the same time.
推荐答案
试试这个:
var array1 = [1, 2, 3, 4, 5, 6],
array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var common = $.grep(array1, function(element) {
return $.inArray(element, array2 ) !== -1;
});
console.log(common); // returns [1, 2, 3, 4, 5, 6];
var array3 = array2.filter(function(obj) { return array1.indexOf(obj) == -1; });
// returns [7,8,9];
这篇关于如何仅在jquery中的2个数组之间找到公共元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!