Get max and min array

0

I wanted to get a maximum and minimum of an Array. The Array comes in PHP and I use Json to convert to JavaScript. I used Math.max.apply(null, js_array) _function but it does not work for me.

//convert php array to javascript
var js_array = [<?php echo '"'.implode('","', $array_nombre).'"' ?>];
    
asked by anonymous 26.12.2014 / 17:54

1 answer

2

Okay, if I understand correctly, you're echoing a string, within [] . Or something like:

var js_array = ['0,1,2,3,4'];

In this case you have to convert this to a "complete" array and then calculate the maximum and minimum.

Test like this:

var js_array = [<?php echo '"'.implode('","', $array_nombre).'"' ?>];
js_array = js_array[0].split(',');

And then you can use:

var js_array = ['0,1,2,3,4'];
js_array = js_array[0].split(',');
var max = Math.max.apply(Math, js_array);
var min = Math.min.apply(Math, js_array);
alert('min: ' + min + ', max: ' + max);
    
26.12.2014 / 17:57