Javascript - Maximum

About

Function - Maximum (Max) in javascript

Snippet

Math.max

  • Numerical order comparison
data=[
     {x: 20, y: "20"}
   , {x: 3, y: "3"}
   ]

let MAX_X = Math.max(...data.map(d => d.x));
let MAX_Y = Math.max(...data.map(d => d.y));

console.log("MAX_X: "+MAX_X)
console.log("MAX_Y: "+MAX_Y)

d3.max

From d3-array

  • d3.max is a the natural order comparison. ie
    • the number 20 is bigger than the number 3
    • but the letter 3 is bigger than the letter 20 (3>2)
  • d3.max ignore NaN or undefined values

Example:

data=[
     {x: 20, y: "20"}
   , {x: 3, y: "3"}
   ]
let MAX_X = d3.max(data, d => d.x);
let MAX_Y = d3.max(data, d => d.y);
console.log("MAX_X: "+MAX_X);
console.log("MAX_Y: "+MAX_Y);
  • Tip, you can use d3-array extent to calculate min and max aggregation in one call.
[MIN_X, MAX_X] = d3.extent(data, d => d.x);
[MIN_Y, MAX_Y] = d3.extent(data, d => d.y);
console.log("MIN_X: "+MIN_X);
console.log("MIN_Y: "+MIN_Y);

Documentation / Reference







Share this page:
Follow us:
Task Runner