2

Using jQuery is there a function that will tell me if the contents of a numeric array are in number order? For example;

[2,5,7,8,9] would return true [5,2,7,8,9] would return false

Scenario: I have an UL which is populated from mysql, the li items are text statements that have been randomly displayed, the id of the li is the rank order number the item should be for a correct sequence. The user then has to reorder the items by drag and drop using jQuery sortable. When the item is dropped I want jQuery to grap the reordered items via serialize into an array which I can then check to see if they are in numeric order which would indicate a correct answer. I've got everything working and I can pass the results back to php to validate to then show the answer in a separate div but I would like to do the checking on the client using jQuery rather than posting back to the server.

Treat me gently I'm a newbie

0

2 Answers 2

1

Here you go try this.

var arr1 = [5,2,7,8,9];
var arr2 = [2,5,7,8,9];

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

console.log(isNumeric(arr1));
console.log(isNumeric(arr2));
Sign up to request clarification or add additional context in comments.

1 Comment

Spot on - thank you very much - I did kind of get there when i tried but was missing the expertise.
0
var array1 = [1, 2, 3, 4, 5, 6];
var array2 = [1, 2, 4, 3, 5, 6];

console.log(checkArrayOrder(array1 ,array2));

function checkArrayOrder(array1 ,array2)
{
    for (var i = 0; i<array2.length; i++) {
        if (array2[i] != array1[i]) {
           return false;
            break;
        }//if close
    }//for close
    return true;
}

Check this FIDDLE

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.