Search code examples
javascriptarrayslodash

Lodash uniqBy update the latest value


I am having an array of objects like below

[
  {
    "id": 27,
    "unread_message_count": 0
  },
  {
    "id": 27,
    "unread_message_count": 7
  }
]

and i use lodash uniqBy to remove the duplicates like below

_.uniqBy(data, 'id')

Which removes the duplicate value like below and returns the result like

{id: 27, "unread_message_count": 0}

Since the second object has some updated value in unread_message_count comparing to first one.I would like to update the unread_message_count as well during the uniq like below

let a = [{id: 27, unread_message_count: 0},{id: 27, unread_message_count: 7}];

_.uniqBy(a, 'id')

Output:

{id: 27, unread_message_count: 7}

Solution

  • You can reverse the array, find the unique values, and then reverse back:

    const arr = [{id: 27, unread_message_count: 0},{id: 27, unread_message_count: 7}];
    
    const result = _.reverse(_.uniqBy(_.reverse([...arr]), 'id'));
    
    console.log(result);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>

    Another option is to reduce the array to a Map, and always take the latest object from identical items:

    const arr = [{id: 27, unread_message_count: 0},{id: 27, unread_message_count: 7}];
    
    const result = Array.from(
      arr.reduce(
        (r, o) => r.set(o.id, o), 
        new Map()
      ).values());
    
    console.log(result);