0
function isSortedAndHow(array) {
  let array_copy=array.slice(0,array.length);
  let ascending_arr=array.sort((a,b)=>{return a-b});
  let descending_arr=array.sort((a,b)=>{return b-a});
  
  //for checking array equality
  function element_check(arr1,arr2){
    return arr1.every((a1,a2)=>{a1===arr2[a2]})
  }
  if(element_check(array,ascending_arr)){
    return "yes,ascending order";
  }
  else if(element_check(array,descending_arr)){
      return "yes,descending order";
  }
  else{
    return "no";
  }
}

I'm trying to accept an array, check if it is sorted in any order and return output. However,the code is returning no all the time.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
  • 3
    you have no return statement in `arr1.every`. btw, it is funny to use arrow functions and then a block with return instead of simple returning a value. – Nina Scholz Jan 25 '21 at 09:10
  • `> ((a) => 1)(5) 1 > ((a) => {1})(5) undefined` – GACy20 Jan 25 '21 at 09:12
  • See [When should I use a return statement in ES6 arrow functions](https://stackoverflow.com/q/28889450). Also, you make `array_copy` but don't use it at all. `ascending_arr`, `descending_arr`, and `array` are all the same array. – VLAZ Jan 25 '21 at 09:16
  • @VLAZ Tht's an other issue with the code. If `element_check` was correct it would always return `yes, ascending order` since all 3 names refer to the same object. Given that it is incorrect it doesn't. – GACy20 Jan 25 '21 at 09:19
  • @GACy20 hence why I mention it in a comment. – VLAZ Jan 25 '21 at 09:19

1 Answers1

2

Because of the various errors

  • missing return statment in arrow function bis block statement,
  • using the same array for checking,
  • taking an superfluous sorting,

you could omit sorting and take a comparison function and iterate the given array directly with a short circuit function and comparison functions for wanted orders.

This approach takes inside of Array#every a check with the previous value or at index zero just true, because this item has no predecessor.

function isSortedAndHow(array) {
    const
        ascending = (a, b) => a <= b,
        descending = (a, b) => a >= b,
        check = (array, fn) => array.every((v, i, a) => !i || fn(a[i - 1], v));

    if (check(array, ascending)) return "yes, ascending order";
    if (check(array, descending)) return "yes, descending order";
    return "no";
}

console.log(isSortedAndHow([0, 1, 2, 5, 4]));
console.log(isSortedAndHow([0, 1, 2, 3, 4]));
console.log(isSortedAndHow([5, 4, 3, 2, 0]));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392