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
JavaScript
x
6
1
0: 55.47999954223633
2
1: 56.040000915527344
3
2: 57.52000045776367
4
3: 57.119998931884766
5
6
Data was extracted from the json file and then put into the array through push.
code is look like this
JavaScript
1
7
1
let Array =[]
2
jQuery.getJSON( "price.json",function(data){
3
for(let i=0;i<data.length;i++){
4
Array.push(data[i].price)
5
}
6
let maximum = Math.max(Array) // not working
7
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:
JavaScript
1
18
18
1
const dataFromJson = [
2
{ name: "A", price: 55.47999954223633 },
3
{ name: "A", price: 56.040000915527344 },
4
{ name: "A", price: 57.52000045776367 },
5
{ name: "A", price: 57.119998931884766 }
6
];
7
8
// ES6:
9
let arr1 = dataFromJson.map(obj => obj.price);
10
let max1 = Math.max(arr1);
11
console.log('ES6 max: ' + max1);
12
13
// ES5:
14
let arr2 = dataFromJson.map(function(obj) {
15
return obj.price;
16
});
17
let max2 = Math.max.apply(null, arr2);
18
console.log('ES5 max: ' + max2);
Output:
JavaScript
1
3
1
ES6 max: 57.52000045776367
2
ES5 max: 57.52000045776367
3