QUery on Return a Sorted Array Without Changing the Original Array

Tell us what’s happening:

I’m curious as to why the below doesn’t work. I’m pretty sure it’s the right solution so I’m blurring it out.
Your code so far


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

  
  // Add your 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/64.0.3282.140 Safari/537.36 Edge/17.17134.

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

try reloading or changin browser, because if I try with your code it does pass

You might try concating an empty array onto the end of the array from the argument, rather than vice versa. So:

var globalArray = [5, 6, 3, 2, 9];
function nonMutatingSort(arr) {
  return arr.concat([]).sort((a,b)=>{
    return a-b;
  })
}

Edit: fixed the closing ), thanks @ChadKreutzer

1 Like

Yeah, both those methods worked when I plugged them in (although @warpfox your solution is missing a )) .

You can reduce the moving parts some though too:

var globalArray = [5, 6, 3, 2, 9];
function nonMutatingSort(arr) {
  return [].concat(arr).sort((a,b)=> a-b);
}

And I get that they want you to use concat() for this lesson, but this happens to be a perfect use case for the spread operator: [...arr].sort((a, b) => a - b)

1 Like