Skip to content
Advertisement

Conditionally concatenate in reducer using lodash

I try to conditionally concat in my reducer, I have an array objects and I want to concatenate only if value not exist in my reducer. If value exists nothing must happen. I use lodash and I tried with _.uniqBy like this :

JavaScript

This does not work.

Example of my reducer

JavaScript

jsFiddle linkk

Required output :

JavaScript

Because val1 ({id:1, name:’alex’}) already exists in the array.

Advertisement

Answer

Concatenating the arrays, and removing duplicates using _.uniqBy() works fine.

Example:

JavaScript
JavaScript

However, it’s better to use _.unionBy() which creates an array of unique values, in order, from all given arrays:

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement