0

i have some arrays like this, the numbers in the array represents slots numbers slots1 = {3,4,5,6} slots2 = {1,2,3,4,5,6} slots3 = {8,9,10}
i am finding whether the selected slots are successive or not.
first two arrays give correct min,max values. but the third array is giving min = 10, max=9. how to rectify it? i am finding maximum value like this

for(var s=0;s<no_slots;s++)//finding maximum value of slots array
        {    
             if(s == 0)
             { 
              var slots_max = slots[s];
             }
             else
             {
                    if(slots[s] > slots_max)
                    {
                      slots_max = slots[s];
                    }
             }              
        }  
gayathri
  • 3
  • 2
  • 4
  • You should declare and initialize `slots_max` before your for loop... – jahroy Jul 16 '13 at 07:45
  • You have a misprint, checking the **slots[s]** but iterating the **no_slots** – udalmik Jul 16 '13 at 07:52
  • @mudalov - Actually, `no_slots` looks like it's just the length of the array. `s` is the correct iterator variable. Presumeably the line before the for loop looks like this: `var no_slots = slots.length;` – jahroy Jul 16 '13 at 07:54
  • Oh, yes. Apologies for confusing. – udalmik Jul 16 '13 at 07:56

3 Answers3

3

Use the JS Math Object:

For the minimum: Math.min.apply(null,slots);
For the maximum: Math.max.apply(null,slots);

KooiInc
  • 119,216
  • 31
  • 141
  • 177
2

I am not sure why you function is not correctly working for your third case. You probably missed something silly like initialization or something similar to that. As I have modified your some code and it is returning correctly. You can also make it shorter.

var slots = [8, 9, 10]
var slots_max = slots[0];
for (var s = 0; s < slots.length; s++) //finding maximum value of slots array
{
   if (slots[s] > slots_max) {
         slots_max = slots[s];
      }
}
alert(slots_max);

Js Fiddle

Sachin
  • 40,216
  • 7
  • 90
  • 102
1

You could instead try finding the minimum/maximum values using the Javascript Math library. This should return the correct result.

var min = Math.min.apply(null, slots3);
var max = Math.max.apply(null, slots3);

See this answer for more details.

Community
  • 1
  • 1
Jamie
  • 3,890
  • 3
  • 26
  • 35