简体   繁体   中英

how to get objects with the same property and has the max value in array - 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);
    }

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

You can use Math.max method in combination with filter and map method.

 let data = [{title: "test1", version: 1}, {title: "test2", version: 3}, {title: "test1", version: 2}, {title: "test2", version: 2}, {title: "test2", version: 1}]; let uniqueTitles = [...new Set(data.map(a => a.title))]; data = uniqueTitles.map(function(key){ return { title:key, version : Math.max(...data.filter(a=>a.title == key).map(a=>a.version)) }; }); console.log(data); 

You can use map from your array of unique titles to get the result you expect:

 const data = [ {title: "test1", version: 1}, {title: "test2", version: 3}, {title: "test1", version: 2}, {title: "test2", version: 2}, {title: "test2", version: 1} ]; const titles = [...new Set(data.map(d => d.title))]; const result = titles.map(title => ({ title, version: Math.max(...data.filter(d => d.title === title).map(d => d.version)) })); console.log(result); 

You can use array#reduce and use a object look up to get highest version number for a given title.

 var data = [{title: "test1", version: 1}, {title: "test2", version: 3}, {title: "test1", version: 2}, {title: "test2", version: 2}, {title: "test2", version: 1}], result = Object.values(data.reduce((r,o) => { r[o.title] = r[o.title] || {version: 0}; if(r[o.title].version < o.version) r[o.title] = o; return r; },{})); console.log(result); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM