Last active
May 18, 2022 06:07
-
-
Save yorkie/7959685 to your computer and use it in GitHub Desktop.
Check if an array is sorted in Javascript...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* check the array is sorted | |
* return: if positive -> 1 | |
* if negative -> -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(); |
function isSorted(array) {
const limit = array.length - 1;
for (let i = 0; i < limit; i++) {
const current = array[i], next = array[i + 1];
if (current > next) { return false; }
}
return true;
}
Inspired by @theQuazz
!![-Infinity,-1,0,2,3,Infinity].reduce((memo, item) => 'boolean' !== typeof memo && item >= memo && item) // true
!![-Infinity,-1,0,2,3,Infinity,2].reduce((memo, item) => 'boolean' !== typeof memo && item >= memo && item) // false
!![0,2,3,4].reduce((memo, item) => 'boolean' !== typeof memo && item >= memo && item) // true
!![0,2,3,4,2].reduce((memo, item) => 'boolean' !== typeof memo && item >= memo && item) // false
ES6
let arr = [-Infinity,-1,0,2,3,Infinity]
arr.slice(1).every((item, i) => arr[i] <= item) // true
arr = [-Infinity,-1,0,2,3,Infinity,2]
arr.slice(1).every((item, i) => arr[i] <= item) // false
function isSorted(boxNumbers) {
for (let i = 1; i < boxNumbers.length; i++) {
if (boxNumbers[i - 1] > boxNumbers[i]) {
return false;
}
}
return true;
}
(formatted by @yorkie)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thx @mattdiamond