'Select the latest unique object from array of objects : Javascript
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 },
]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
