Javascript的算法找到数组不在另一个数组元素 [英] Javascript algorithm to find elements in array that are not in another array

查看:120
本文介绍了Javascript的算法找到数组不在另一个数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个好的算法来获得一个数组不在另一个数组元素的所有元素。因此,考虑到这些阵列:

 变种X = [A,B,C,T];
变种Y = [D,一个,T,E,克];
 

我想结束了这阵:

 变种Z = [D,E,G];
 

我使用jQuery,这样我就可以利用 $的。每一个() $。inArray()。这是我想出来的解决方案,但似乎应该有一个更好的办法。

  //目标是摆脱在y值,如果他们以x存在
变种X = [一个,B,C,吨];
变种Y = [D,一个,T,E,克];

变种Z = [];
$每个(Y,功能(IDX,值){
  如果($ .inArray(值,X)==  -  1){
    z.push(值);
  }
});
警报(Z); //应该是[D,E,G]
 

下面是 code在行动。任何想法?

解决方案

 变种Z = $ .grep(Y,函数(EL){返回$ .inArray(EL,X)= = -1});
 

此外,该方法名是太短了自己的好。我希望这意味着isElementInArray,不是的indexOf。

有关使用对象的演示,请参见 http://jsfiddle.net/xBDz3/6/

I'm looking for a good algorithm to get all the elements in one array that are not elements in another array. So given these arrays:

var x = ["a","b","c","t"];
var ​​​​​​​​​y = [​​​​​​​"d","a","t","e","g"];

I want to end up with this array:

var z = ["d","e","g"];

I'm using jquery, so I can take advantage of $.each() and $.inArray(). Here's the solution I've come up with, but it seems like there should be a better way.

// goal is to get rid of values in y if they exist in x
var x = ["a","b","c","t"];
var y = ["d","a","t","e","g"];

var z = [];
$.each(y, function(idx, value){
  if ($.inArray(value,x) == -1) {
    z.push(value);
  }
});
​alert(z);  // should be ["d","e","g"]

Here is the code in action. Any ideas?

解决方案

var z = $.grep(y, function(el){return $.inArray(el, x) == -1}); 

Also, that method name is too short for its own good. I would expect it to mean isElementInArray, not indexOf.

For a demo with objects, see http://jsfiddle.net/xBDz3/6/

这篇关于Javascript的算法找到数组不在另一个数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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