Return a Sorted Array Without Changing the Original Array - Confused as the purpose of this Exercise

Tell us what’s happening:
I am lost as to the functional programming method for this challenge. I have tried it separately in a browser console and my solution works and sort is acting on a new array.

The solution given by the hint has concat and the sort function acts directly on the arr that is passed into the function.

My issue is that my solution, the given solution, and just straight up “return arr.sort()” all do not effect the globalArray variable. It returns the unsorted array each time.

I want to know what this challenge is trying to teach, and why concat, because I cannot figure it out.

Your code so far


var globalArray = [5, 6, 3, 2, 9];
function nonMutatingSort(arr) {
  // Add your code below this line
  var newArr = arr;
  return newArr.sort();
  
  // Add your code above this line
}
nonMutatingSort(globalArray);

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/functional-programming/return-a-sorted-array-without-changing-the-original-array

You can use concat to make a copy of the array.
Right now by using

var newArr = arr

if i’m right, you are just pointing to the global array.

With concat you can create an empty array and then concat the parameter arr.

var newArr = arr;

This isn’t copying the array, it’s the same array.

Your solution changes the content of globalArray.

This assignment here

var newArr = arr;

is still referencing the original array, and not a copy of it. So any manipulation you do to your local variable, will change the original one as well

var globalArray = [5, 6, 3, 2, 9];
function nonMutatingSort(arr) {
  // Add your code below this line
  var newArr = arr;
  return newArr.sort();
  
  // Add your code above this line
}
nonMutatingSort(globalArray);
console.log('globalArray is ',globalArray)
// globalArray is  [ 2, 3, 5, 6, 9 ]

That’s why the solution uses a method that don’t change the original one, but returns a new one :slight_smile:

Thank you very much, it makes more sense now.