Skip to content
Advertisement

How to get max and min value from Array in Javascript?

i had seen lots of another examples like

Math.max(...Array1) or Math.max(null,num) or Math.max.apply(null,num)
but it’s not working by my code
my data size is 255 and This is what the data looks like when i print it by console.log

0: 55.47999954223633
1: 56.040000915527344
2: 57.52000045776367
3: 57.119998931884766
...

Data was extracted from the json file and then put into the array through push.
code is look like this

let Array =[]
jQuery.getJSON( "price.json",function(data){
        for(let i=0;i<data.length;i++){
             Array.push(data[i].price)
        }    
let maximum = Math.max(...Array) // not working 

Thank you for reading this.

Advertisement

Answer

Math.max(...[]) is ES6 syntax. Maybe you are using an older JavaScript engine? Here are two versions using your data as input, one for newer ES6, one for older ES5:

const dataFromJson = [
  { name: "A", price: 55.47999954223633 },
  { name: "A", price: 56.040000915527344 },
  { name: "A", price: 57.52000045776367 },
  { name: "A", price: 57.119998931884766 }
];

// ES6:
let arr1 = dataFromJson.map(obj => obj.price);
let max1 = Math.max(...arr1);
console.log('ES6 max: ' + max1);

// ES5:
let arr2 = dataFromJson.map(function(obj) {
  return obj.price;
});
let max2 = Math.max.apply(null, arr2);
console.log('ES5 max: ' + max2);

Output:

ES6 max: 57.52000045776367
ES5 max: 57.52000045776367
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement