prosource

배열에서 다른 배열에 없는 요소를 찾기 위한 Javascript 알고리즘

probook 2023. 9. 5. 20:38
반응형

배열에서 다른 배열에 없는 요소를 찾기 위한 Javascript 알고리즘

저는 다른 배열의 요소가 아닌 한 배열의 모든 요소를 가져올 수 있는 좋은 알고리즘을 찾고 있습니다.따라서 다음과 같은 어레이가 제공됩니다.

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

작동 중인 코드가 여기 있습니다.아이디어 있어요?

간단히 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))

새로운 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;
});
var z = $.grep(y, function(el){return $.inArray(el, x) == -1}); 

또한, 그 메소드 이름은 너무 짧아서 쓸모가 없습니다.인덱스 Of가 아닌 Element InArray를 의미할 것으로 예상됩니다.

개체를 사용한 데모는 http://jsfiddle.net/xBDz3/6/ 를 참조하십시오.

다음은 언더스코어.js를 사용한 대안입니다.

function inAButNotInB(A, B) {
  return _.filter(A, function (a) {
    return !_.contains(B, a);
  });
}

지금은 많이 늦었지만 누군가에게 도움이 될 것 같습니다.

배열이 단순 배열이 아니라 객체 배열인 경우 다음을 사용할 수 있습니다.

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"

이것은 늦은 답변이지만, 도서관을 사용하지 않기 때문에 어떤 사람들은 도움이 될 수 있습니다.

/**
 * Returns a non-destructive Array of elements that are not found in
 * any of the parameter arrays.
 *
 * @param {...Array} var_args   Arrays to compare.
 */
Array.prototype.uniqueFrom = function() {
  if (!arguments.length)
    return [];
  var a1 = this.slice(0); // Start with a copy

  for (var n=0; n < arguments.length; n++) {
    var a2 = arguments[n];
    if (!(a2 instanceof Array))
      throw new TypeError( 'argument ['+n+'] must be Array' );

    for(var i=0; i<a2.length; i++) {
      var index = a1.indexOf(a2[i]);
      if (index > -1) {
        a1.splice(index, 1);
      } 
    }
  }
  return a1;
}

예:

var sheetUsers = ['joe@example.com','fred@example.com','sam@example.com'];
var siteViewers = ['joe@example.com','fred@example.com','lucy@example.com'];
var viewersToAdd = sheetUsers.uniqueFrom(siteViewers);  // [sam@example.com]
var viewersToRemove = siteViewers.uniqueFrom(sheetUsers);  // [lucy@example.com]
 findDiff = (A, B) => {
     return  A.filter(function (a) {
          return !B.includes(a);
     });
 }

배열의 정렬된 복사본을 먼저 만듭니다.상단 요소가 동일하면 두 요소를 모두 제거합니다.그렇지 않으면 더 작은 요소를 제거하고 결과 배열에 추가합니다.한 배열이 비어 있으면 다른 배열의 나머지를 결과에 추가하고 마침합니다.요소를 제거하는 대신 정렬된 배열을 반복할 수 있습니다.

// assume x and y are sorted
xi = 0; yi = 0; xc = x.length; yc = y.length;
while ( xi < xc && yi < yc ) {
  if ( x[xi] == y[yi] ) {
    xi += 1;
    yi += 1;
  } else if ( x[xi] < y[yi] ) {
    z.push( x[xi] );
    xi += 1;
  } else {
    z.push( y[yi] );
    yi += 1;
  }
}
// add remainder of x and y to z.  one or both will be empty.

jLinq가 도와줄 수 있을까요?

Javascript 개체에 대해 이와 같은 쿼리를 실행할 수 있습니다.

예:

var users = [ { name: "jacob", age: 25 },  { name: "bob" , age: 30 }]
var additionalusers = [ { name: "jacob", age: 25 },  { name: "bill" , age: 25 }]

var newusers = jLinq.from(users).except(additionalusers).select();

>>> newusers = [ { name: "bob" , age: 30 } ]

현재로서는 다소 지나친 감이 있지만, 제가 알게 되어 기뻤던 강력한 해결책입니다.

그것은 교차, 결합, 부울 논리, 그리고 모든 종류의 훌륭한 linq 스타일의 선량함을 처리할 수 있습니다.

언급URL : https://stackoverflow.com/questions/2963281/javascript-algorithm-to-find-elements-in-array-that-are-not-in-another-array

반응형