Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get objects with the same property and has the max value in array - Javascript

Tags:

javascript

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);
    }
like image 735
Nik D Avatar asked Nov 08 '22 12:11

Nik D


1 Answers

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

like image 66
Lusito Avatar answered Nov 15 '22 11:11

Lusito