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];
                    }
             }              
        }  
4
  • You should declare and initialize slots_max before your for loop...
    – jahroy
    Commented Jul 16, 2013 at 7:45
  • You have a misprint, checking the slots[s] but iterating the no_slots
    – udalmik
    Commented Jul 16, 2013 at 7: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
    Commented Jul 16, 2013 at 7:54
  • Oh, yes. Apologies for confusing.
    – udalmik
    Commented Jul 16, 2013 at 7:56

3 Answers 3

3

Use the JS Math Object:

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

0
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

1
  • Do we really require that else condition ? We can make that if (inside the else) stand- alone.
    – Amin Sayed
    Commented Jul 16, 2013 at 8:00
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.