I am a beginner in JS writing code, and I have a question about the isSorted function.
I am supposed to use for-of-loop in the code.
Here is the task:
Declare a function isSorted.
/**
* @param {Array<number>} ??? - an array of numbers
* @returns {boolean} whether or not the given array is sorted
*/
Here is what i wrote
function isSorted(array) {
const result = [];
for (const number of array) {
if (number < number1 && number2 ) {
result.push(number);
}
return true;
}
}
Here is the error message that I get
Here is the test that I could not pass with my code above
actual = isSorted([1, 2, 3]);
expected = true;
if (actual === expected) {
console.log("Test PASSED.");
} else {
console.error("Test FAILED. Keep trying!");
console.group("Result:");
console.log(" actual:", actual);
console.log("expected:", expected);
console.groupEnd();
}
actual = isSorted([3, 2, 3]);
expected = false;
if (actual === expected) {
console.log("Test PASSED.");
} else {
console.error("Test FAILED. Keep trying!");
console.group("Result:");
console.log(" actual:", actual);
console.log("expected:", expected);
console.groupEnd();
}
You can compare the i-th element of the array with the next one. If one element is greater than the following the array is not sorted
function isSorted(array) {
for (let i = 0; i < array.length; ++i) {
if (array[i + 1]) {
if (array[i] > array[i + 1]) {
return false;
}
}
}
return true;
}
Or you can reduce your array to a boolean value (see Array.prototype.reduce()):
function isSorted(array) {
return array.reduce((prev, cur) => prev !== false && cur >= prev && cur)
}
where prev is the the value resulting from the previous iteration and cur the current iteration item.
Try this isSorted function:
function isSorted(array) {
let previousNo = null;
for (const number of array) {
if (previousNo != null && number < previousNo) {
return false;
}
previousNo = number;
}
return true;
}
It still uses the for..of loop, and here's what it's doing:
This fuction compare array members: first with second, second with third...etc. If the following member of the array is less than the actual, return false(array is not sorted).
function isSorted(array) {
for (var i = 0; i<array.length; i++) {
if (array[i] > array[i+1]) {
return false;
}
}
return true;
}