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.
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.