Skip to content Skip to sidebar Skip to footer

Compare Two Array Of Objects Javascript And Throw The Unmatched Array Elements Into New Array Using Underscore Or Lodash

I have two arrays apple = [1,5,10,15,20], bottle = [1,5,10,15,20,25] using lodash or any javascript function, I want an array c with unique elements c= [25]. To be more precise, I

Solution 1:

You could use Array#filter with a Set of the opposite array.

This proposal uses a complement function which returns true if the element a is not in the set b.

For a symmetric difference, the filtering with callback has to be used for both sides.

functiongetComplement(collection) {
    // initialize and close over a set created from the collection passed invar set = newSet(collection);
    // return iterator callback for .filter()returnfunction (item) {
        return !set.has(item);
    };
}
var apple = [1,5,10,15,20], 
    bottle = [1,5,10,15,20,25],
    unique = [
        ...apple.filter(getComplement(bottle)),
        ...bottle.filter(getComplement(apple))
    ];

console.log(unique);

Solution 2:

You can create your own function with reduce() and filter() for this.

var apple = [1,5,10,15,20], bottle = [1,5,10,15,20,25] 

functiondiff(a1, a2) {
  //Concat array2 to array1 to create one array, and then use reduce on that array to return//one object as result where key is element and value is number of occurrences of that elementvar obj = a1.concat(a2).reduce(function(result, element) {
    result[element] = (result[element] || 0) + 1return result
  }, {})
  
  //Then as function result return keys from previous object where value is == 1 which means that// that element is unique in both arrays.returnObject.keys(obj).filter(function(element) {
    return obj[element] == 1
  })
}

console.log(diff(apple, bottle))

Shorter version of same code with ES6 arrow functions.

var apple = [1,5,10,15,20], bottle = [1,5,10,15,20,25] 

functiondiff(a1, a2) {
  var obj = a1.concat(a2).reduce((r, e) => (r[e] = (r[e] || 0) + 1, r), {})
  returnObject.keys(obj).filter(e => obj[e] == 1)
}

console.log(diff(apple, bottle))

Post a Comment for "Compare Two Array Of Objects Javascript And Throw The Unmatched Array Elements Into New Array Using Underscore Or Lodash"