javascript - 从包含多个对象的数组中返回编号最大的对象
问题描述
我能够弄清楚如何从具有多个对象的关联数组中返回最高数字。但我需要整个对象。
我准备了这个例子:
var data = [
{ nr: 235, text: "foo" }
,{ nr: 351, text: "bar" }
];
var highestNr = Math.max.apply(null, Object.keys(data).map(function(e) {
return data[e]['nr'];
}));
var index = "???";
console.log("Highest 'nr': " + highestNr);
console.log("Index at nr "+ highestNr + ": " + index);
//console.log(data[index]);
我需要索引或整个对象。我需要显示来自具有最高数字的对象的文本。
解决方案
您可以通过选择具有更大值的数组来减少数组。
var data = [{ nr: 235, text: "foo" }, { nr: 351, text: "bar" }],
topNr = data.reduce((a, b) => a.nr > b.nr ? a : b);
console.log(topNr);
推荐阅读
- javascript - Node/Express:使用来自另一个文件的函数请求
- tensorflow - 在 Google Coral Devboard 和 Jetson Nano 中使用我自己构建的卷积神经网络分类器
- javascript - Spring DWR engine.js 失败未知错误
- symfony - 弃用模板必须包含“%service_id%”占位符
- java - 将 JSON 序列化程序设置为使用单引号而不是双引号来附加值
- c# - C# FtpWebRequest 失败,成功时抛出异常
- dpdk - pkt-gen dpdk 不发送任何数据包问题
- java - 警告消息:不推荐在文档索引请求中指定类型
- python - 检测器 2 输出的类标签指的是什么?
- javascript - Docker-Compose : 来自具有相同 Dockerfile 的本地图像的多个服务