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

烈酒焚心 提交于 2019-12-09 05:28:13

问题


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


回答1:


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);
});



回答2:


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;
}



回答3:


var last = undefined,
    sorted = true;
_.forEach(arr, function(val) {
    if(last !== undefined && val < last) sorted = false;
    last = val;
});
alert(sorted);



回答4:


I found this very helpful link.

/*
* check the array is sorted
* return: if sorted in ascending ->  1
*         if sorted in descending -> -1
*         not sorted  ->  0
*/

Array.prototype.isSorted = function() {
  return (function(direction) {
  return this.reduce(function(prev, next, i, arr) {
    if (direction === undefined)
      return (direction = prev <= next ? 1 : -1) || true;
    else
      return (direction + 1 ?
        (arr[i-1] <= next) : 
        (arr[i-1] >  next));
    }) ? Number(direction) : false;
  }).call(this);
}

var arr = [3,2,1,0];
arr.isSorted(); // Will return -1



回答5:


A simple es6 code:

const arr = [1, 2, 3]
const arr2 = [3, 2, 1]

function isSorted (arr) {
  return arr.slice(1).every((item, i) => arr[i] <= item)
}

console.log(isSorted(arr), isSorted(arr2))



回答6:


I found solution in pure js with every:

//Array is sorted
[1, 2, 3].every( (item, i, arr) => i < arr.length - 1 ? arr[i] < arr[i + 1] : arr[i] ); //true
[3, 2, 1].every( (item, i, arr) => i < arr.length - 1 ? arr[i] < arr[i + 1] : arr[i] ); //false

//Equolent
[1, 2, 3].every( (item, i, arr) => i > 0 ? arr[i] > arr[i - 1] : arr[i] < arr[i + 1] ); //true


来源:https://stackoverflow.com/questions/10914982/check-if-a-list-is-sorted-in-javascript-using-underscore-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!