mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2025-12-19 18:18:27 -05:00
84 lines
1.7 KiB
Markdown
84 lines
1.7 KiB
Markdown
---
|
|
id: 69373793f5a867f769cde136
|
|
title: "Challenge 151: Sorted Array?"
|
|
challengeType: 28
|
|
dashedName: challenge-151
|
|
---
|
|
|
|
# --description--
|
|
|
|
Given an array of numbers, determine if the numbers are sorted in ascending order, descending order, or neither.
|
|
|
|
If the given array is:
|
|
|
|
- In ascending order (lowest to highest), return `"Ascending"`.
|
|
- In descending order (highest to lowest), return `"Descending"`.
|
|
- Not sorted in ascending or descending order, return `"Not sorted"`.
|
|
|
|
# --hints--
|
|
|
|
`isSorted([1, 2, 3, 4, 5])` should return `"Ascending"`.
|
|
|
|
```js
|
|
assert.equal(isSorted([1, 2, 3, 4, 5]), "Ascending");
|
|
```
|
|
|
|
`isSorted([10, 8, 6, 4, 2])` should return `"Descending"`.
|
|
|
|
```js
|
|
assert.equal(isSorted([10, 8, 6, 4, 2]), "Descending");
|
|
```
|
|
|
|
`isSorted([1, 3, 2, 4, 5])` should return `"Not sorted"`.
|
|
|
|
```js
|
|
assert.equal(isSorted([1, 3, 2, 4, 5]), "Not sorted");
|
|
```
|
|
|
|
`isSorted([3.14, 2.71, 1.61, 0.57])` should return `"Descending"`.
|
|
|
|
```js
|
|
assert.equal(isSorted([3.14, 2.71, 1.61, 0.57]), "Descending");
|
|
```
|
|
|
|
`isSorted([12.3, 23.4, 34.5, 45.6, 56.7, 67.8, 78.9])` should return `"Ascending"`.
|
|
|
|
```js
|
|
assert.equal(isSorted([12.3, 23.4, 34.5, 45.6, 56.7, 67.8, 78.9]), "Ascending");
|
|
```
|
|
|
|
`isSorted([0.4, 0.5, 0.3])` should return `"Not sorted"`.
|
|
|
|
```js
|
|
assert.equal(isSorted([0.4, 0.5, 0.3]), "Not sorted");
|
|
```
|
|
|
|
# --seed--
|
|
|
|
## --seed-contents--
|
|
|
|
```js
|
|
function isSorted(arr) {
|
|
|
|
return arr;
|
|
}
|
|
```
|
|
|
|
# --solutions--
|
|
|
|
```js
|
|
function isSorted(arr) {
|
|
let ascending = true;
|
|
let descending = true;
|
|
|
|
for (let i = 1; i < arr.length; i++) {
|
|
if (arr[i] < arr[i - 1]) ascending = false;
|
|
if (arr[i] > arr[i - 1]) descending = false;
|
|
}
|
|
|
|
if (ascending) return "Ascending";
|
|
if (descending) return "Descending";
|
|
return "Not sorted";
|
|
}
|
|
```
|