简体   繁体   中英

Get object from array by max property

I need to perform in JavaScript what in C# would look like this:

var latest = versions.OrderByDescending( v => v.VersionNo).First();

I want this done via Math.max method and although it should be trivial task I am struggling to get it correct. I've gone through web and several questions here but can't make it work.

So basically, you want to find the object in versions with the highest VersionNo .

Sounds like a job for Array#reduce :

var latest = versions.reduce(function(l, e) {
  return e.VersionNo > l.VersionNo ? e : l;
});

 var versions = [ {VersionNo: 3}, {VersionNo: 7}, {VersionNo: 1} ]; var latest = versions.reduce(function(l, e) { return e.VersionNo > l.VersionNo ? e : l; }); console.log(latest); 

When you call it as above (with just one argument, the callback to use), Array#reduce calls your callback with the first two entries, and then again for each subsequent entry with the first argument being the return value of the previous call and the second being the next entry in the array. The result is the final return value of the last callback.

Clear as mud? That means if you call it on an array with [1, 2, 3, 4] your callback will be called with 1, 2 , then r, 3 where r is whatever it returned, then r, 4 where r is whatever it returned the last time. (If you give a second argument to reduce , it uses that as the initial value for r and just does r, 1 , then r, 2 , ...)

So in the above, we return the object with the higher VersionNo of the two arguments from the callback, which will eventually give us the first one with the highest value. (I say "first one" because if you have more than one with the same value, we'll take the first.)

Or in ES2015+:

let latest = versions.reduce((l, e) => e.VersionNo > l.VersionNo ? e : l);

 let versions = [ {VersionNo: 3}, {VersionNo: 7}, {VersionNo: 1} ]; let latest = versions.reduce((l, e) => e.VersionNo > l.VersionNo ? e : l); console.log(latest); 

You can get the max value of a property in an object with the following

var latest = (Math.max.apply(Math, versions.map(function(v) {
  return v.VersionNo;
})));

Documentation on .map() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

There are many answers to this. Since you didn't specify I can show yo multiple options:

  1. Jquery.grep
  2. .Map
  3. Math.Max

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