Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lodash union of arrays of objects

I'd like to use the _.union function to create a union of two arrays of objects. Union works with arrays of primitives only as it uses === to examine if two values are equal.

I'd like to compare objects using a key property: objects with the same key property would be regarded equal. Is there a nice functional way to achieve that ideally using lodash?

like image 538
Janos Avatar asked Mar 28 '15 18:03

Janos


People also ask

How do I merge arrays in Lodash?

Lodash helps in working with arrays, strings, objects, numbers, etc. The _. merge() method is used to merge two or more objects starting with the left-most to the right-most to create a parent mapping object.

How do I compare two arrays in Lodash?

isEqual() Method. The Lodash _. isEqual() Method performs a deep comparison between two values to determine if they are equivalent. This method supports comparing arrays, array buffers, boolean, date objects, maps, numbers, objects, regex, sets, strings, symbols, and typed arrays.

What is _ get?

The _. get() function is an inbuilt function in the Underscore. js library of JavaScript which is used to get the value at the path of object. If the resolved value is undefined, the defaultValue is returned in its place. Syntax: _.get(object, path, [defaultValue])


3 Answers

A non pure lodash way to do this but using the array.concat function you are able to do this pretty simply along uniq():

var objUnion = function(array1, array2, matcher) {
  var concated = array1.concat(array2)
  return _.uniq(concated, false, matcher);
}

An alternative approach would be to use flatten() and uniq():

var union = _.uniq(_.flatten([array1, array2]), matcherFn);
like image 94
Craig Suchanec Avatar answered Sep 17 '22 05:09

Craig Suchanec


And what about UniqBy with a concat of the two arrays before?

import _ from 'lodash'

const arrayUnion = (arr1, arr2, identifier) => {
  const array = [...arr1, ...arr2]

  return _.uniqBy(array, identifier)  
 }


const array1 = [{ id: 1 }, { id: 2 }, { id: 3 }]
const array2 = [{ id: 3 }, { id: 4 }, { id: 4 }]

console.log(arrayUnion(array1, array2, 'id'))

result → [{ 'id': 1 }, { 'id': 2 }, { 'id': 3 }, { 'id': 4 }]

like image 41
MatthieuH Avatar answered Sep 17 '22 05:09

MatthieuH


Late to the party but _.unionWith is much better in doing what you want.

var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];

_.unionWith(objects, others, _.isEqual);
// => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]
like image 42
alaboudi Avatar answered Sep 18 '22 05:09

alaboudi