0

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.

kaiser
  • 19,898
  • 15
  • 82
  • 102
user3703539
  • 377
  • 1
  • 4
  • 19

2 Answers2

1

I have tried, what you have done , it is working perfectly fine .

You can try this as well,

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

1

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>
Ori Drori
  • 145,770
  • 24
  • 170
  • 162