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

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

问题描述

我正在寻找一种好的算法来获取一个数组中不是另一个数组中的元素的所有元素.所以给定这些数组:

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"];

我想得到这个数组:

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

我正在使用 jquery,所以我可以利用 $.each()$.inArray().这是我想出的解决方案,但似乎应该有更好的方法.

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"]

这是代码.有什么想法吗?

推荐答案

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

此外,该方法名称太短了.我希望它表示 isElementInArray,而不是 indexOf.

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

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

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

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

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