How to get objects with the same property and has the max value in array I have a data like
data = [{title: "test1", version: 1},
{title: "test2", version: 3},
{title: "test1", version: 2},
{title: "test2", version: 2},
{title: "test2", version: 1}];
And I want the result
result = [{title: "test1", version: 2},
{title: "test2", version: 3}];
Is there any better ways than what I did here?
var titles = [...new Set(data.map(o=> o.title))];
var recentVersions = [];
for(var i = 0; i < titles.length; i++){
var recentVersion = null;
for(var j = 0; j < data.length; j++){
if(titles[i] === data[j].title){
if(!recentVersion){
recentVersion = data[j];
}else if (recentVersion.version < data[j].version){
recentVersion = data[j];
}
}
}
recentVersions.push(recentVersion);
}
You should look up array methods like map, filter and in this case reduce:
let result = data.reduce((r, x)=> {
if(!r[x.title] || r[x.title].version < x.version)
r[x.title] = x;
return r;
}, {});
(this is of course an object map, depending on your use-case you need to get the values with a call to Object.values(result)
or could iterate over the object itself
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With