javascript - 可以将 math.max 用于对象数组吗?

标签 javascript node.js typescript

我看到这样的答案,用于获取数组中的最大数字,

var arr = [1, 2, 3];
var max = Math.max(...arr);

但是对一个对象数组执行此操作怎么样,每个对象都有一个数字字段,如下所示

class test {
   number: x
   other_fields
}

var arr = [test1, test2, test3];
var max = Math.max(...arr);

最佳答案

首先使用.map将对象数组转换为数字数组:

var max = Math.max(
  ...arr.map(obj => obj.number)
);

const obj1 = {
   number: 2,
   prop: 'val'
};
const obj2 = {
   number: 2,
   prop: 'val'
};

var arr = [obj1, obj2];
var max = Math.max(
  ...arr.map(obj => obj.number)
);
console.log(max);

如果您需要一个对象而不仅仅是数字,请使用 reduce 代替:

const obj1 = {
   number: 2,
   prop: 'val'
};
const obj2 = {
   number: 2,
   prop: 'val'
};

var arr = [obj1, obj2];
const largestObj = arr.reduce((a, obj) => a.number > obj.number ? a : obj);
console.log(largestObj);

关于javascript - 可以将 math.max 用于对象数组吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60471435/

相关文章:

javascript - Backbone.js:将事件绑定(bind)到模板按钮

javascript - Firebase云函数返回错误错误: There is no user record corresponding to the provided identifier

javascript - 通过 webpack 从 typescript 导出对象并在 JS 中使用

javascript - 为什么不允许以逗号分隔的 var 声明属性?

javascript - 表单验证规则动态变化

javascript - YAML 1.2 anchor 在 js-yaml 3.10.0 中不起作用?

typescript - 省略对象中所有 `undefined` 的属性

javascript - Typescript 中的编译错误

javascript - 如何限制 AJAX API 免于不必要的使用(例如执行 SELECT * 的人)

node.js - bcrypt compare 需要一分多钟才能完成