我正在寻找一个好的算法来获得一个数组中的所有元素,而不是另一个数组中的元素。因此,给定这些数组:
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"]
这是code in action。有什么想法吗?
发布于 2010-06-03 12:18:09
var z = $.grep(y, function(el){return $.inArray(el, x) == -1});
此外,该方法的名称太短,不利于其自身的好处。我希望它指的是isElementInArray,而不是indexOf。
有关对象的演示,请参阅http://jsfiddle.net/xBDz3/6/
发布于 2017-07-05 14:10:16
在ES6中,只需
const a1 = ["a", "b", "c", "t"];
const a2 = ["d", "a", "t", "e", "g"];
console.log( a2.filter(x => !a1.includes(x)) );
(另一个选项是a2.filter(x => a1.indexOf(x)===-1)
)
发布于 2014-02-17 16:05:28
新的ECMA5 javascript的最新答案:
var x = ["a","b","c","t"];
var y = ["d","a","t","e","g"];
myArray = y.filter( function( el ) {
return x.indexOf( el ) < 0;
});
https://stackoverflow.com/questions/2963281
复制相似问题