javascript - 如何从 Array / Angular 中的元素中获取最小值
问题描述
我有以下数组
[
0: {
nameId: "041c1119"
lastError: null
spotId: "15808822"
workType: "1"
},
1: {
nameId: "041c1130"
lastError: null
spotId: "15808821"
workType: "1"
},
2: {
nameId: "041c11123"
lastError: null
spotId: "15808820"
workType: "1"
}
]
我正在尝试获得最低spotId
值,在这种情况下,我需要获得15808820
. 我将不胜感激任何建议的帮助(使用 lodash 的示例会很棒)谢谢!
解决方案
不需要任何像 Lodash 这样的外部库,您可以在纯 JS 中实现结果。
Array.reduce()
这是使用 ES6 特性和方法的一行代码的解决方案。
const data = [{
nameId: "041c1119",
lastError: null,
spotId: "15808822",
workType: "1"
}, {
nameId: "041c1130",
lastError: null,
spotId: "15808821",
workType: "1"
}, {
nameId: "041c11123",
lastError: null,
spotId: "15808820",
workType: "1"
}];
const minSpotId = data.reduce((prev, current) => (prev.spotId < current.spotId) ? prev : current);
console.log(minSpotId);
推荐阅读
- google-cloud-platform - 尝试重新创建 cloudsql 实例时出现错误“项目中的资源是冲突的主题”的原因是什么?
- c# - 我可以将 ics 文件发送给 Outlook 与会者,将与会者状态更新为接受/拒绝吗
- python - 如何使用 webpy 在 python 中修复 500 Internal Server Error?
- objective-c - 绑定套接字时出错:NSPOSIXErrorDomain Code=1 "Operation not allowed"
- swagger - 如何在调用 Rest Endpoint 时在 Swagger 中设置输入参数选项
- php - PHP:如果 MYSQL Result 大于 0,添加到数组中?
- process - 内核的超参数;初始化和设置边界
- c# - 获取名称中包含此字符串的文件的完整路径
- java - @Valid 在使用没有控制器的杰克逊创建对象时
- python - for循环计数器,报告1