user3599444
user3599444

Reputation: 145

Without array of objects

I am trying to implement a function similar to lodash _.without but it should work with array of objects:

function withoutArrayOfObjects (arr1, arr2) {
  var resultArr = [];
  for (var i = 0; i < arr1.length; i++) {
    for (var j = 0; j < arr2.length; j++) {
      if (!_.isEqual(arr1[i], arr2[j])) {
        resultArr.push(arr1[i]);
      }
    }
  }
  return resultArr;
}

It woks fine in this case:

var array1 = [{0: 'test', 1: 'test2'}, {0: 'test3', 1: 'test4'}];
var array2 = [{0: 'test', 1: 'test2'}];
withoutArrayOfObjects(array1, array2);

However it fails if array contains two objects:

var array3 = [{0: 'test', 1: 'test2'}, {0: 'test3', 1: 'test4'}, {0: 'test5', 1: 'test6'}, {0: 'test7', 1: 'test8'}];
var array4 = [{0: 'test', 1: 'test2'}, {0: 'test5', 1: 'test6'}];
withoutArrayOfObjects(array3, array4);

Could you help me to fix / improve the function? Either with plain JS or jquery/lodash.

Upvotes: 0

Views: 41

Answers (1)

Louay Alakkad
Louay Alakkad

Reputation: 7408

Try this (ES6):

resultArr = arr1.filter(obj1 => {
  return !arr2.some(obj2 => _.isEqual(obj1, obj2));
});

Or in ES5:

resultArr = arr1.filter(function (obj1) {
  return !arr2.some(function (obj2) { 
    return _.isEqual(obj1, obj2); 
  });
});

i.e. We create a new array from arr1 by filtering out items which have some equivalents in arr2.

Upvotes: 2

Related Questions