[英]How to find the min/max of values in an array of json objects (javascript)
I have a JSON array that looks something like this:我有一个 JSON 数组,看起来像这样:
arr = [{"range":4, "time":56, id:"a4bd"},
{"range":5, "time":65, id:"a4bg"},
{"range":3, "time":58, id:"a4cd"},
{"range":3, "time":57, id:"a4gh"},
{"range":8, "time":60, id:"a5ab"}]
I'd like to know the best way in javascript to find the minimum or maximum value for one of these properties, eg.我想知道 javascript 中找到这些属性之一的最小值或最大值的最佳方法,例如。
min(arr["time"])
or something similar, which would return 56或类似的东西,它会返回 56
Use Math.max
and Math.min
with array将
Math.max
和Math.min
与数组一起使用
Reference参考
These functions will return the minimum/maximum values from a list of input numbers.这些函数将从输入数字列表中返回最小/最大值。
what you have to do is generate the list od numbers against which you need to find min or max.您需要做的是生成列表 od 数字,您需要根据这些数字找到最小值或最大值。 I used
Array.map
to return the vaues from each node of array.我使用
Array.map
从数组的每个节点返回值。 Spread the array to a list of numbers and apply Math.min
and Math.max
将数组扩展到数字列表并应用
Math.min
和Math.max
const arr = [{ "range": 4, "time": 56, id: "a4bd" }, { "range": 5, "time": 65, id: "a4bg" }, { "range": 3, "time": 58, id: "a4cd" }, { "range": 3, "time": 57, id: "a4gh" }, { "range": 8, "time": 60, id: "a5ab" }]; function findMinMax(key) { const datas = arr.map((node) => node[key]); return { min: Math.min(...datas), max: Math.max(...datas), } } console.log(findMinMax('range')); console.log(findMinMax('time'));
For example lodash solution for minimum option:例如最小选项的lodash解决方案:
import _ from 'lodash';
const myMin = (arr, prop) => _.minBy(arr, (o) => o[prop])[prop];
myMin(arr, 'time'); // 56
myMin(arr, 'range'); // 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.