# Return a Sorted Array Without Changing the Original Array

Tell us what’s happening:
I know I’m missing something obvious to complete this challenge, but with the code below, I keep getting the following error message:

“nonMutatingSort(globalArray) should return [2, 3, 5, 6, 9].”

Please can someone put me out of my misery and help me with the correct code?

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

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

You are copying your array twice.
If you print newArray to the console, you will see the following array: [5, 6, 3, 2, 9, 5, 6, 3, 2, 9];
This causes your answer to be wrong. All you need to do is remove “globalArray” from your concat function.

1 Like

Of course - thank you!

This is my solution:

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

I came up with this easy solution

var globalArray = [5, 6, 3, 2, 9];
function nonMutatingSort(arr) {
var newArray = arr.concat();
return newArray.sort();

}
nonMutatingSort(globalArray);

1 Like

Guys you don’t read the instructions

`<code >return globalArray.concat([]).sort() </code>`

1 Like

I would rather use arr instead of GlobalArray - this is more functional programming way - lets you use this function with other arrays.

1 Like

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

Here is my code

``````var globalArray = [5, 6, 3, 2, 9];
function nonMutatingSort(arr) {
let array = [].concat(arr)
array.sort()

return [].concat(array)