如何找到共同的元素只有在jQuery的2阵列之间 [英] How to find common elements only between 2 arrays in jquery

查看:138
本文介绍了如何找到共同的元素只有在jQuery的2阵列之间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 变种ARRAY1 = [1,2,3,4,5,6]。
变种数组2 = [1,2,3,4,5,6,7,8,9];

我有两个数组像上面。现在我想用jQuery做以下的MVC 4。


  1. 如果两个数组的元素每次都相等,则显示消息/警报。例如所有的记录已经存在。


  2. 如果两个数组元素的每一个都不同则只需添加他们都在一个VAR,例如 VAR的ResultSet = .... (其中7,8,9将存储)


  3. 如果两个数组之间的共同然后为共同的元素一些因素显示一条消息,以元素,例如记录1,2,3,4,5,6已经存在,并在VAR添加不同的元素,例如 VAR的ResultSet = .... (其中7,8,9将存储)。无论是消息和差异性的元素集合将在同一时间进行。



解决方案

  

试试这个:


 变种ARRAY1 = [1,2,3,4,5,6]中
    数组2 = [1,2,3,4,5,6,7,8,9];VAR共同= $ .grep(数组1,函数(元素){
    返回$ .inArray(元素,数组2)== -1!;
});的console.log(共同); //返回[1,2,3,4,5,6]。VAR ARRAY3 = array2.filter(函数(OBJ){返回array1.indexOf(OBJ)== -1;});//返回[7,8,9]。

var array1 = [1, 2, 3, 4, 5, 6];
var array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9];

I have two arrays like above. Now I want to do the following in MVC 4 with jQuery.

  1. If every elements of both arrays are equal then show a message/alert. e.g. "All records already existing."

  2. 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)

  3. 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.

解决方案

Try this:

    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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆