-1

I have this array and it is formatted as string:

['identifier','6.35', '2.72', '11.79', '183.25']

The first item is always 'identifier' so must be filtered out.

What I need in this example as output is:

MaxValue = 183.25
MinValue = 2.72

What would be a clean and fast way to achieve this? My arrays can contain a lot of data.

hacking_mike
  • 1,005
  • 1
  • 8
  • 22

2 Answers2

0

You can to start by filtering out anything that is not numeric. You can then find the min and max as an aggregation. You could also optimize this by checking for a numeric during the aggregation to save scanning over the array once upfront):

const input = ['identifier','6.35', '2.72', '11.79', '183.25']

const result = input.filter( x => !isNaN(x)).reduce( (acc, x) => {
 acc.max = Math.max(acc.max,x);
 acc.min = Math.min(acc.min,x); 
 return acc;
}, {min: Number.POSITIVE_INFINITY, max: Number.NEGATIVE_INFINITY})

console.log(result);

Or if you prefer you can pass the resulting array to the Math.min and Math.max functions

const input = ['identifier','6.35', '2.72', '11.79', '183.25']

const nums = input.filter( x => !isNaN(x));

console.log(Math.max(...nums));
console.log(Math.min(...nums));
Jamiec
  • 133,658
  • 13
  • 134
  • 193
  • This works great. One additional question. Is it possible to have the min value be the first number above 0? – hacking_mike Jun 20 '22 at 11:13
  • let nums = parentstockGraphData.graphlegperc[0].filter( x => !isNaN(x) ); nums = nums.filter( x => x!=0) alert(Math.max(...nums)); alert(Math.min(...nums)); – hacking_mike Jun 20 '22 at 12:00
0

Scan the array only once

let data = ["identifier", "6.35", "2.72", "11.79", "183.25"];

function minMax(data) {
  let min = Infinity;
  let max = -Infinity;

  for (let s of data) {
    let n = Number.parseFloat(s);
    if (Number.isNaN(n)) continue;
    if (min > n) min = n;
    if (max < n) max = n;
  }
  return [min, max];
}

console.log(minMax(data));
holydragon
  • 6,158
  • 6
  • 39
  • 62