0

I am trying to test if an array is sorted in ascending order using the JS every method: checking if every element is smaller than the next index.

I don't understand why my code below is not working.

const testArray1 = [1, 2, 3, 4, 5, 6];
const testArray2 = [25, 51, 32, 12, 15];

const isAscending = (element, index, array) => {element < array[index + 1]};

console.log(testArray1.every(isAscending));// expecting true, but getting false

console.log(testArray2.every(isAscending));// expecting false, getting false

I am aware that the sort method exists, this is for a school exercice.

  • What happens when the last number is compared with undefined? – Yousaf Feb 17 '23 at 10:01
  • 1
    Do you get an error in the console? Perhaps index+1 results in an IndexOutOfBoundsException for the last element, as there is no last + 1. – morsor Feb 17 '23 at 10:01
  • When you are at the last element you try to compare it with the length+1 which is out of bounds. This returns false – Manos Kounelakis Feb 17 '23 at 10:02
  • 1
    @morsor — JavaScript arrays are dynamic. Undefined values are just `undefined`. Accessing them doesn't raise an exception. – Quentin Feb 17 '23 at 10:05
  • https://stackoverflow.com/questions/53833139/check-array-in-js-is-list-sorted – pmpc Feb 17 '23 at 10:05
  • Does this answer your question? [When should I use a return statement in ES6 arrow functions](https://stackoverflow.com/questions/28889450/when-should-i-use-a-return-statement-in-es6-arrow-functions) – pilchard Feb 17 '23 at 10:13

1 Answers1

2

You have two problems.

  1. Your arrow function always returns undefined because it is missing a return statement.
  2. You are comparing the last value in the array to undefined (e.g. when i is 5 for the first array, element is 6 and array[5 + 1] is undefined) which is always false so you need to implement a special case for that entry.
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335