1

I am trying to write a simple function that will test if a an array is consecutive but for some reason it does not work. This is a small part of an angular JS app if that's relevant.

        return function isConsecArray(arr){
          var i;
          var y = (arr.length);       
         for (i=0; i < y; i += 1){
         if (parseInt(arr[i])+1 !== parseInt(arr[i+1]))
         {
         return false;
         }

         }
         return true;       

2 Answers 2

3

When reaching the last element, i.e. i=y-1, it compares arr[i] with arr[i+1], which is undefined. You need to iterate up to arr.length-1, i.e.:

...
for (i=1; i < y-1; i += 1) { / NOTE THE y-1 LIMIT
...
Sign up to request clarification or add additional context in comments.

Comments

0

You could write it like this:

function isConsecArray(arr) {
    var previous = arr[0];
    var i;
    var y = (arr.length);
    if (y > 1) {
        for (i=1; i < y; i += 1) {
            if (parseInt(arr[i]) -1  !== parseInt(previous)) {
                return false;
            }
            previous = arr[i];        
        }
    }
    return true;
}

JSFiddle: http://jsfiddle.net/dq1kccvk/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.