通过max属性从数组获取对象 [英] Get object from array by max property

查看:99
本文介绍了通过max属性从数组获取对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在JavaScript中执行C#中的内容:

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

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

我希望通过Math.max方法完成此操作,尽管这应该是微不足道的任务,但我仍在努力使其正确.我在网上浏览了几个问题,但无法正常工作.

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.

推荐答案

因此,基本上,您想在versions中找到具有最高VersionNo的对象.

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

听起来像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);

当您按上述方式调用它(仅使用一个参数,即要使用的回调)时,Array#reduce会使用前两个条目调用回调,然后对于每个后续条目再次调用,第一个参数是上一个调用,第二个是数组中的下一个条目.结果是最后一个回调的最终返回值.

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.

像泥一样清晰吗?这意味着,如果使用[1, 2, 3, 4]在数组上调用它,则将使用1, 2调用回调,然后使用r, 3,其中r是它返回的值,然后是r, 4,其中r是它返回的最后一个值时间. (如果给reduce提供第二个参数,它将使用它作为r的初始值,而r, 1则使用它,然后r, 2,...)

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, ...)

因此,在上面的代码中,我们从回调函数中返回两个参数中具有较高VersionNo的对象,这将最终为我们提供第一个具有最高值的对象. (我说第一个",因为如果您有多个具有相同值的值,我们将采用第一个.)

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

或在ES2015 +中:

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

这篇关于通过max属性从数组获取对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆