diff --git a/snippets/isArraySorted.md b/snippets/isArraySorted.md new file mode 100644 index 000000000..005b4be78 --- /dev/null +++ b/snippets/isArraySorted.md @@ -0,0 +1,23 @@ +### functionName + +Returns `1` if the array is sorted in ascending order, `-1` if it is sorted in descending order or `0` if it is not sorted. + +Calculate the ordering `direction` for the first two elements. +Use `Object.entries()` to loop over array objects and compare them in pairs. +Return `0` if the `direction` changes or the `direction` if the last element is reached. + +```js +const isArraySorted = arr => { + const direction = arr[0] > arr[1] ? -1 : 1; + for(let [i, val] of arr.entries()) + if (i === arr.length - 1) return direction; + else if ((val - arr[i + 1]) * direction > 0) return 0; +} +``` + +```js +isArraySorted([0,1,2,3]) // 1 +isArraySorted([0,1,2,2]) // 1 +isArraySorted([4,3,2]) // -1 +isArraySorted([4,3,5]) // 0 +``` diff --git a/tag_database b/tag_database index 94f7a6330..8163643ee 100644 --- a/tag_database +++ b/tag_database @@ -71,6 +71,7 @@ isAbsoluteURL:string isArmstrongNumber:math isArray:utility isArrayLike:utility +isArraySorted:array isBoolean:utility isDivisible:math isEven:math