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.

5
  • 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. Commented Jan 25, 2021 at 9:10
  • > ((a) => 1)(5) 1 > ((a) => {1})(5) undefined Commented Jan 25, 2021 at 9:12
  • See When should I use a return statement in ES6 arrow functions. Also, you make array_copy but don't use it at all. ascending_arr, descending_arr, and array are all the same array. Commented Jan 25, 2021 at 9: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. Commented Jan 25, 2021 at 9:19
  • @GACy20 hence why I mention it in a comment. Commented Jan 25, 2021 at 9:19

1 Answer 1

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]));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.