我正在寻找一种好的算法来获取一个数组中不是另一个数组中的元素的所有元素。所以给定这些数组:
var x = ["a","b","c","t"];
var y = ["d","a","t","e","g"];
我想以这个数组结束:
var z = ["d","e","g"];
我正在使用 jquery,所以我可以利用$.each()
和$.inArray()
。这是我想出的解决方案,但似乎应该有更好的方法。
// 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"]
这是正在运行的代码。有任何想法吗?