I have a JSON array that looks something like this:
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.
min(arr["time"])
or something similar, which would return 56
CodePudding user response:
Use Math.max
and Math.min
with array
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. I used Array.map
to return the vaues from each node of array. Spread the array to a list of numbers and apply Math.min
and 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'));
CodePudding user response:
For example lodash solution for minimum option:
import _ from 'lodash';
const myMin = (arr, prop) => _.minBy(arr, (o) => o[prop])[prop];
myMin(arr, 'time'); // 56
myMin(arr, 'range'); // 3