user3348410
user3348410

Reputation: 2833

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)

Upvotes: 4

Views: 1672

Answers (2)

Jack Bashford
Jack Bashford

Reputation: 44087

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);

Upvotes: 3

Ori Drori
Ori Drori

Reputation: 191976

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>

Upvotes: 3

Related Questions