5

I'm trying to concat two arrays of objects with lodash. I have these two array and I use concat operator in this way:

 var array1 = [{ id: 1, name: 'doc1' }, { id: 2, name: 'doc2' }];
 var array2 = [{id:1, name:'doc1'}, {id:3, name:'doc3'}, {id:4, name:'doc4'}];

 var array3 = _.concat(array1, array2);

I would like an array like this

 [{id:1, name:'doc1'}, {id:2, name:'doc2'}, {id:3, name:'doc3'}, {id:4, name:'doc4'}]]

But with concat function I obtain an array like this:

  [{ id: 1, name: 'doc1' }, { id: 1, name: 'doc1' }, { id: 2, name: 'doc2' }, { id: 3, name: 'doc3' }, { id: 4, name: 'doc4' }]]

I want to avoid the repetition of an object with the same id...Which kind of operator can I use?

3 Answers 3

11

You can get the result using merge and keyBy lodash functions.

var array1 = [{id:1, name:'doc1'}, {id:2, name:'doc2'}];
var array2 = [{id:1, name:'doc1'}, {id:3, name:'doc3'}, {id:4, name:'doc4'}];

var merged = _.merge(_.keyBy(array1, 'id'), _.keyBy(array2, 'id'));
var values = _.values(merged);
console.log(values);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

Sign up to request clarification or add additional context in comments.

Comments

2

Use _.unionBy() to combine two arrays, and remove duplicates that have the same unique field (id in this case). The lodash's union methods create an array of unique values. The _.unionBy() method accepts an iteratee which is invoked for each element of each array to generate the criterion by which uniqueness is computed.

const array1 = [{id:1, name:'doc1'}, {id:2, name:'doc2'}];
const array2 = [{id:1, name:'doc1'}, {id:3, name:'doc3'}, {id:4, name:'doc4'}];

const result = _.unionBy(array1, array2, 'id');
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

Comments

1

You have uniqWith in lodash that allows you to do this: https://lodash.com/docs#uniqWith

var array1 = [{id:1, name:'doc1'}, {id:2, name:'doc2'}];
var array2 = [{id:1, name:'doc1'}, {id:3, name:'doc3'}, {id:4, name:'doc4'}];

var values = _.uniqWith([...array1, ...array2], _.isEqual);
console.log(values);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.