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

Tell us what’s happening:

Can anyone tell me why this wouldn´t work?
For globalArray it works but not for another array.

Your code so far

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

function nonMutatingSort(arr) {
  // Only change code below this line

return [...arr].sort();

  // Only change code above this line

console.log(nonMutatingSort([1, 30, 4, 21, 100000]))

Your browser information:

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

Challenge Information:

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


This is a great question.

Your function (below) appears to sort your defined globalArray:

However, when you submit [1, 30, 4, 21, 100000], it gives a curious result.

Interestingly, if you add another element to the globalArray as follows you will see a similar curious result:

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

This is normal according to the documentation since the sort method converts the elements to string and compares the elements according to character codes. Essentially, sort() performs an alphabetical sort.

Array.prototype.sort()The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

To sort numerically, you need to use a different technique. A hint here is that the sort method can also take a function as an argument (see the link above).

Also, the sort() method sorts in place and hence modifies the original array. Another hint is to make a copy of the array to a new one and then do the sort.

Does this help?
Keep up the good progress!

Happy Coding! :slightly_smiling_face:


That clarified it for me.
I already got the correct code, I was just curious why this wasn´t working.
Thanks a lot for your detailed answer!

1 Like

Glad to be of assistance, @deucenn . Keep on coding brother!

1 Like