Lodash union of arrays of objects
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 }]