Functional Programming - Return a Sorted Array Without Changing the Original Array

Tell us what’s happening:

Why does this code only work for the first array but not the other two arrays? They are all just trying to return numbers in ascending order.

Your code so far

const globalArray = [5, 6, 3, 2, 9];

function nonMutatingSort(arr) {
  // Only change code below this line
  [...arr].sort(function(a, b) {
     a === b ? 0 : a < b ? -1 : 1;
  });
  return [...arr].sort();
  // Only change code above this line
}

console.log(nonMutatingSort(globalArray));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36

Challenge: Functional Programming - Return a Sorted Array Without Changing the Original Array

Link to the challenge:

This line is the only line that returns something, but the sort converts the numbers to strings and sorts them which does not end up sorting them correctly.

This line correctly sorts a copy of arr but does not return it.

Thank you very much!