Return a Sorted Array Without Changing the Original Array problem

Tell us what’s happening:

I am trying to sort this array without mutating it. But my solution is not correct. What am I missing?

return [].concat(arr).sort((a, b) => (a - b));

When I wrote this code into the function, it is accepted. But the code in the below is not. What is difference?

Your code so far


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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0.

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

concat is not mutating sArr, so sArr is still an empty array and you are sorting an empty array.
Add some console.log() to your code to see what I mean:

var sArr = [];
console.log(sArr + ' this is sArr before concat');
  sArr.concat(arr);
console.log(sArr + ' this is sArr after concat');
console.log(sArr.concat(arr) + ' this is what you want instead, how do you use this?');
1 Like

(remember that concat returns a new array)

Always pay close attention to the hints in the challenge description.

sArr.concat(arr)

.concat() doesn’t mutate the array. It returns a new one. That’s why it’s being used here to avoid mutating the original array.

Hi,
can you explain the difference between the return statements, the commented code does not work why?

var globalArray = [5, 6, 3, 2, 9];
function nonMutatingSort(arr) {
  // Add your code below this line
  let newarr = [];
 return newarr.concat(arr).sort(function(a, b) {
   return a - b;
 });

//  let newarr = [];
//   newarr.concat(arr).sort(function(a, b) {
//    return a - b;
//  });
//   return newarr;

}
nonMutatingSort(globalArray);

In the commented code, you are not sorting newarr, you are sorting the array returned by .concat, then returning newarr which is still empty. The uncommented code is also sorting the array returned by .concat, but it’s returning that array rather than newarr