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?
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.
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.
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])
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);
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 }]
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 }]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With