0

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

2 Answers 2

2

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'));

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.