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];
};
Update: realized I can just logical or the reduce one:
const rtn = notes.reduce((acc, note) => {
if (
acc.maxTimestamp === undefined ||
note.lastEdit > acc.maxTimestamp
) {
acc = { maxTimestamp: note.lastEdit, maxId: note.id };
}
return acc;
}, {}).maxId;
I still like the simple version better but let me know what you think or if you can think of something simpler : )
Update 2: Even simpler:
const rtn = notes.reduce(
(acc, note) =>
acc.maxTimestamp === undefined || note.lastEdit > acc.maxTimestamp
? { maxTimestamp: note.lastEdit, maxId: note.id }
: acc,
{}
).maxId;
or:
const rtn = notes.reduce(
(acc, note) =>
note.lastEdit > acc.maxTimestamp
? { maxTimestamp: note.lastEdit, maxId: note.id }
: acc,
{ maxTimestamp: -1 }
).maxId;
sortfunction on the array to sort by timestamp? would be aO(nlogn) for a O(n) problem though \$\endgroup\$return notes.sort((a, b) => b.lastEdit - a.lastEdit)[0].id;be considered bad code? \$\endgroup\$sortway runs seemingly instantly with 250 items, which is the max I allow my users (could change) \$\endgroup\$sortmutates the original object, but that's fine in this case. Worth noting for others viewing this in the future. \$\endgroup\$