Skip to main content
1 of 2
Justin
  • 129
  • 3

Find a property of an object in array of objects with the min/max number in another property

So I have notes that have a lastEdit which is a timestamp in milliseconds and a unique id. I want to find the id of the note that has the greatest lastEdit value.

I tried the good old fashion way, and then figured there must be an es6 way of doing this, but even after a lot of struggling and getting it to work, it's even messier.

I'm wondering if there's a cleaner / better way of doing this. I don't care about ties in timestamp or performance much. Here's what I got so far:

const getMostRecentNote = () => {
    let maxTimestamp = 0;
    let maxId = -1;
    notes.forEach((n) => {
        if (maxTimestamp < n.lastEdit) {
            maxTimestamp = n.lastEdit;
            maxId = n.id;
        }
    });

    // https://stackoverflow.com/a/43576363/4907950
    const rtn = notes.reduce((acc, note) => {
        if (acc.maxTimestamp === undefined) {
            acc = { maxTimestamp: -1, maxId: -1 };
        }
        if (note.lastEdit > acc.maxTimestamp) {
            acc = { maxTimestamp: note.lastEdit, maxId: note.id };
        }
        return acc;
    }, {}).maxId;

    return [maxId, rtn];
};
```
Justin
  • 129
  • 3