zmaten zmaten - 3 months ago 6
Javascript Question

Get object from array by max property

I need to perform 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.

Answer

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);