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

Tell us what’s happening:
Describe your issue in detail here.

Your code so far
Why is the callback needed(for the last two tests to pass) if sort already sorts in ascending order without a callback?
Also, is there any difference whether .concat(arr) is used or arr.concat()?

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

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

nonMutatingSort(globalArray);

Your browser information:

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

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

Link to the challenge:

https://devdocs.io/javascript/global_objects/array/sort

see description for unicode chars

you could also simplify the code a little imho:

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

function nonMutatingSort(arr) {
  
  const newArr=arr.slice(0)
  newArr.sort((a, b) => a - b);
  return newArr
  
}

console.log(globalArray) 
1 Like