Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a list is sorted in javascript using underscore.js

In javascript (underscore) , how do I test whether a list of numbers is already sorted or not?

like image 661
Lorraine Bernard Avatar asked Jun 06 '12 13:06

Lorraine Bernard


2 Answers

You can use _.every to check whether all elements are in order:

_.every(arr, function(value, index, array) {
  // either it is the first element, or otherwise this element should 
  // not be smaller than the previous element.
  // spec requires string conversion
  return index === 0 || String(array[index - 1]) <= String(value);
});
like image 73
pimvdb Avatar answered Oct 13 '22 00:10

pimvdb


A simple solution would be to simply iterate over the list, examining whether each element is smaller than its next neighbor:

function is_sorted(arr) {
    var len = arr.length - 1;
    for(var i = 0; i < len; ++i) {
        if(arr[i] > arr[i+1]) {
            return false;
        }
    }
    return true;
}
like image 21
valderman Avatar answered Oct 12 '22 23:10

valderman