If I have
const foo = [
{ id: 1234, b: 'blah', v: 1 },
{ id: 1234, b: 'blahr', v: 3 },
{ id: 1234, b: 'blag', v: 2 }
]
const latest = foo.reduce((a, b) => (a.v > b.v ? a : b));
console.log(latest);
// { a: 1234, b: 'blahr', v: 3 }
update: fixed a typo in the code above
all is good so far. But I actually have
const foo = [
{ id: 1234, b: 'blah', v: 1 },
{ id: 1234, b: 'blahr', v: 3 },
{ id: 1234, b: 'blag', v: 2 },
{ id: 3424, b: 'gaaar', v: 1 },
{ id: 5324, b: 'moorg' },
]
and I want
[
{ id: 1234, b: 'blahr', v: 3 },
{ id: 3424, b: 'gaaar', v: 1 },
{ id: 5324, b: 'moorg' }
]
In other words, I want the reduce
function to apply only if there are more than one objects with the same id
. Objects with unique ids, and objects without any version v
info should be returned as is.
Update2: Ok, using the answer to Most efficient method to groupby on an array of objects and combining my reduce
function above, I am able to accomplish what I want with the following code:
const groupBy = function(xs, key) {
return xs.reduce((rv, x) => {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
bar = groupBy(foo, 'id');
baz = Object.values(bar).map(e => e.reduce((a, b) => (a.v > b.v ? a : b)));
console.log(baz)
//[ { id: 1234, b: 'blahr', v: 3 },
//{ id: 3424, b: 'gaaar', v: 1 },
//{ id: 5324, b: 'moorg' } ]