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