0

Why do ascending and descending arrays give the same output? Anyone can solve this?

function isSortedAndHow(arr) {
  let asc = arr.sort((a, b) => a - b); // Ascending order , yes
  let dsc = arr.sort((a, b) => b - a); // descending array, yes

  if (arr == asc) {
    console.log("Ascending , Yes");
  } else if (arr == dsc) {
    console.log("Descending , Yes");
  } else {
    console.log("No");
  }
}
isSortedAndHow([25,20,15,30,35]);
Smit Gabani
  • 240
  • 2
  • 6
  • another issue is that array is sorted in-place, so the initial array is changed as well https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort – vladtkachuk Jun 24 '22 at 19:06
  • @Andy, they aren't different objects (which is the problem, `arr == asc` will always be true), `sort()` returns a reference to the original array (after sorting in place) – pilchard Jun 24 '22 at 20:54

0 Answers0