Return sort array not working

Good day, can you see the problem with my code? Thank you!

  **Your code so far**

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

// Only change code above this line
}
console.log(nonMutatingSort([140000, 104, 99]));

// concat an empty array to the one being sorted
// run sort on new array

  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36.

Challenge: Return a Sorted Array Without Changing the Original Array

Link to the challenge:

You are referencing the global variable and neglecting the input arr.

Also, calling this variable a str is very confusing.

Gotcha. Thank you.

I’m still getting used to callbacks. For some reason that part hasn’t fully clicked yet even though I understand it’s gotta be the input in the function. Also the globalArray confused me because it’s not actually being used if I understand correctly

This issue doesn’t have anything to do with callbacks. Your callback function for sort is fine. You are referencing a global variable instead of the function arguments.

I see, what’s the purpose of having the globalArray there?

It was part of the original sample test case:

var globalArray = [5, 6, 3, 2, 9];
function nonMutatingSort(arr) {
  // Only change code below this line


  // Only change code above this line
}
nonMutatingSort(globalArray);

Having a global variable holding a test case array helps make it a little bit easier to test that you didn’t mutate the input when your sort.

Something like:

var globalArray = [5, 6, 3, 2, 9];
function nonMutatingSort(arr) {
  // ...
}
console.log(globalArray);
console.log(nonMutatingSort(globalArray));
console.log(globalArray);
1 Like

Ok got it. Thank you

1 Like