Get max and min array

Asked

Viewed 184 times

0

I wanted to get the maximum and minimum of an Array. The Array comes in PHP and I use Json to convert to Javascript. I used the Math.max.apply(null, js_array) but it doesn’t work for me.

//convert php array to javascript
var js_array = [<?php echo '"'.implode('","', $array_nombre).'"' ?>];
  • Also put the code that goes next to the client. Already after PHP.

  • The code that comes after PHP, is the one that is in the question.

  • The values are well inserted, what is done is converted the php array to the javascript string

  • This makes no sense. The code after PHP no longer has PHP. How does this array look in the HTML page if you see the source code?

  • I don’t see JSON involved in array conversion...

1 answer

2


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

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

Then you have to convert it into a "full" array and then calculate the maximum and minimum.

Forehead 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);

  • In my case it does not work. Because it is converted into a string.

  • @akm edited the answer...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.