Javascript算法查找数组中不在另一个数组中的元素

Tau*_*ren 29 javascript arrays algorithm jquery

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

var x = ["a","b","c","t"];
var ?????????y = [???????"d","a","t","e","g"];
Run Code Online (Sandbox Code Playgroud)

我想最终得到这个数组:

var z = ["d","e","g"];
Run Code Online (Sandbox Code Playgroud)

我正在使用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"]
Run Code Online (Sandbox Code Playgroud)

这是代码的实际应用.有任何想法吗?

Mau*_*ark 53

使用新的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;
});
Run Code Online (Sandbox Code Playgroud)

  • 关于算法复杂性/可扩展性的任何想法? (3认同)

kof*_*fus 22

在ES6中简单

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

console.log( y.filter(e => !x.includes(e)) );
Run Code Online (Sandbox Code Playgroud)

(另一种选择是y.filter(e => x.indexOf(e)===-1))


Mat*_*hen 12

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

此外,该方法名称太短,不适合自己的好处.我希望它的意思是isElementInArray,而不是indexOf.

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


Mat*_*elk 12

这是使用underscore.js的替代方法:

function inAButNotInB(A, B) {
  return _.filter(A, function (a) {
    return !_.contains(B, a);
  });
}
Run Code Online (Sandbox Code Playgroud)


Ahm*_*rMH 12

我现在很晚了,但也许这会对某人有帮助。

如果数组不仅仅是一个简单的数组,而是一个对象数组,那么可以使用以下内容:

var arr1 = [
    {
      "prop1": "value1",
      "prop2": "value2",
    },
    {
      "prop1": "value3",
      "prop2": "value4",
    },
    {
      "prop1": "value5",
      "prop2": "value6",
    },
  ];

var arr2 = ['value1','value3', 'newValue'];

// finds all the elements of arr2 that are not in arr1
arr2.filter( 
    val => !arr1.find( arr1Obj => arr1Obj.prop1 === val)
); // outputs "newValue"

Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

24060 次

最近记录:

6 年,10 月 前