Conditionally concatenate in reducer using lodash

Tags: , ,



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 :

_.uniqBy(arr1.concat(val1), 'id');

This does not work.

Example of my reducer

const arr1 = [{id:1, name:'alex'}, {id:2, name:'taylor'}]
const val1 = {id:1, name:'alex'};

const reducer = {
    finalArr: arr1.concat(val1)
}

console.log('Reducer', reducer)

jsFiddle linkk

Required output :

[{id:1, name:'alex'}, {id:2, name:'taylor'}]

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

Answer

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

Example:

const arr1 = [{id:1, name:'alex'}, {id:2, name:'taylor'}]
const val1 = {id:1, name:'alex'};

const result = _.uniqBy(arr1.concat(val1), 'id');

console.log('Reducer', result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

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

const arr1 = [{id:1, name:'alex'}, {id:2, name:'taylor'}]
const val1 = {id:1, name:'alex'};

const result = _.unionBy(arr1, val1, 'id');

console.log('Reducer', result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>


Source: stackoverflow