Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lodash uniqWith, how say lodash keep last duplicate

Hello i'm using lodash uniqWith method for remove duplicated items which have same id in my array.

but lodash keep first duplicated item. But i wan't to keep last duplicated item.

what can i do for that ?

var result = _.uniqWith(editedData, function(arrVal, othVal) {
      return arrVal.id === othVal.id;
    });
    console.log(result)
like image 668
user3348410 Avatar asked Sep 16 '25 15:09

user3348410


2 Answers

You can create a uniqByLast function using _.flow(). Use _.keyBy() to get an object by id, and _.values() to get an an array:

const { flow, partialRight: pr, keyBy, values } = _

const lastUniqBy = iteratee => flow(
  pr(keyBy, iteratee),
  values
)

const arr = [{ id: 1, val: 1 }, { id: 1, val: 2 }, { id: 2, val: 1 }, { id: 2, val: 2 }]

const result = lastUniqBy('id')(arr)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

And the same idea using lodash/fp:

const { flow, keyBy, values } = _

const lastUniqBy = iteratee => flow(
  keyBy(iteratee),
  values
)

const arr = [{ id: 1, val: 1 }, { id: 1, val: 2 }, { id: 2, val: 1 }, { id: 2, val: 2 }]

const result = lastUniqBy('id')(arr)

console.log(result)
<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>
like image 173
Ori Drori Avatar answered Sep 19 '25 07:09

Ori Drori


Easiest way? Reverse the array first (after cloning it to avoid mutation).

var result = _.uniqWith(_.reverse(_.clone(editedData)), function(arrVal, othVal) {...});

You can also simplify your code:

var result = _.uniqWith(_.reverse(_.clone(editedData)), ({ id: a }, { id: b }) => a === b);
like image 25
Jack Bashford Avatar answered Sep 19 '25 05:09

Jack Bashford