[can't pass] Return a Sorted Array Without Changing the Original Array

Hi everyone,

I’m struggling with the challenge “Return a Sorted Array Without Changing the Original Array” and would be most grateful for any help from the community, thanks in advance.

(link: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/functional-programming/return-a-sorted-array-without-changing-the-original-array)

I’ve come up with two ways to solve the problem and when I test my code outside of freeCodeCamp, I get the results I’m looking for. But when I copy the code into fCC, I can’t seem to pass all the “tests”.

My approach 1:

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

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

  return globalArray.slice().sort((a, b) => a - b);
  // Only change code above this line
}

nonMutatingSort(globalArray);

My approach 2:

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

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

  let emptyArray = [];

  let combinedArray = globalArray.concat(emptyArray);

  return combinedArray.sort((a, b) => a - b);
  // Only change code above this line
}

nonMutatingSort(globalArray);

In both approaches, I’m unable to pass the last two “tests” in the challenge.

I understand with my first approach, I don’t concatenate an empty array, so that might be a problem.

But I’m having trouble understanding why my second approach also doesn’t work.

Would anyone be able to shed some light on what I’m doing wrong?

Thanks again.

you are given a variable arr
but you are completely ignoring it
(you are using the global variable globalArray instead and that’s why the tests are failing)

2 Likes

@hbar1st , thank you!!! I have no idea why I overlooked the parameter “arr”, it’s like I didn’t even see it… :scream: :scream: :rofl: :rofl:

Thanks again for your help. Both of my approaches work when I change “globalArray” to “arr”.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.