Home > Back-end >  Select the latest unique object from array of objects : Javascript
Select the latest unique object from array of objects : Javascript

Time:02-21

I am having array of objects with the following structure

const arr = [
  { id: 0, name: "abc", userid: "0", lastseen: 1645079273000 },
  { id: 3, name: "pqr", userid: "456", lastseen: 1645079273008 },
  { id: 1, name: "lmn", userid: "123", lastseen: 1645079273001 },
  { id: 3, name: "pqr", userid: "456", lastseen: 1645079273002 },
  { id: 4, name: "xyz", userid: "123", lastseen: 1645079273003 },
];

I want to return the objects where userid that is unique with latest entry should be returned. Ideally I might get userId as string 0. so to remove that added a filter clause

My approach:

const result = [...new Map(arr.filter(node=>node.userid!=="0").map(node=>[node.userid, node])).values()];

Output expected

[
  { id: 4, name: "xyz", userid: "123", lastseen: 1645079273003 },
  { id: 3, name: "pqr", userid: "456", lastseen: 1645079273008 },
]

CodePudding user response:

Array.reduce implementation.

Logic

  • Run a loop on tha array using Array.reduce.
  • Create an object and update the value against key userId.
  • Produce the Array.values of this generated object. This will give you the unique list of values.

const arr = [
  { id: 0, name: "abc", userid: "0", lastseen: 1645079273000 },
  { id: 3, name: "pqr", userid: "456", lastseen: 1645079273008 },
  { id: 1, name: "lmn", userid: "123", lastseen: 1645079273001 },
  { id: 3, name: "pqr", userid: "456", lastseen: 1645079273002 },
  { id: 4, name: "xyz", userid: "123", lastseen: 1645079273003 },
];
const result = Object.values(arr.reduce((acc, curr) => {
  if (curr.userid !== "0") {
    acc[curr.userid] = acc[curr.userid] && acc[curr.userid].lastseen ?
      acc[curr.userid].lastseen < curr.lastseen ? curr : acc[curr.userid] : curr;
  }
  return acc;
}, {}));
console.log(result)

  • Related