0

My problem is that I have an array with numbers and I want to get the highest number that is lower than e.g. 6.

So if I have an array like this:

10, 5, 19, 2, 1, 32, 3

I only want to get the number 5.

I tried to sort the array from highest to lowest like this:

str = "<?php echo $timings;?>"
res = str.split(",");
res.sort(function(a, b){return b-a});
alert(res);

But I never figured out a way to get the first value lower than x.

Robert
  • 10,403
  • 14
  • 67
  • 117

3 Answers3

1

You've shown:

res = "<?php echo $timings;?>"
res.sort(function(a, b){return b-a});

That would be a string by the time it gets to JavaScript. If what the browser sees is:

res = "10, 5, 19, 2, 1, 32, 3"
res.sort(function(a, b){return b-a});

...then the first step is to turn that string into an array, which you can do like this:

var a = res.split(/[,\s]+/);

Then, just loop through the array and look:

var lowest;
a.forEach(function(num) {
    if (num < 6 && (lowest === undefined || lowest > num)) {
        lowest = num;
    }
});

That's using ES5's forEach, which nearly all environments now have (but IE8 doesn't). Details on how to loop through arrays can be found in this other Stack Overflow question and its answers.

Or if you need to know the index of the lowest number:

var a = [10, 5, 19, 2, 1, 32, 3];
var lowest, lowestIndex = -1;
a.forEach(function(num, index) {
    if (num < 6 && (lowest === undefined || lowest > num)) {
        lowest = num;
        lowestIndex = index;
    }
});
Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

If you are getting data from PHP anyways why not return the value instead of array?

You could first remove the array elements that are greater than X:

$filtered = array_filter($timings, function ($x) { return $x < $y; });

Now you are left with an array that contains elements that are less than or equal to x

Now just get the max value:

$max = max($filtered);

GGio
  • 7,563
  • 11
  • 44
  • 81
  • why did I get vote down? OP clearly is getting an array from PHP, you can not just apply JS functions to a variable that holds a PHP array ? – GGio Jun 06 '14 at 16:49
0

First you need to convert string like looking array to real array using .split(/[,\s]+/).

Then you can just use Math.max along with Array.prototype.filter.

Like this:

var res = "<?php echo $timings;?>".split(/[,\s]+/);
var num = Math.max.apply(null,res.filter(function(x){
   return  x < 6
}));

Basically what the above does is find all numbers less than 6 using .filter() and then taking the largest number from the returned array using Math.max

Amit Joki
  • 58,320
  • 7
  • 77
  • 95