# Return a Sorted Array Without Changing the Original Array

Return a Sorted Array Without Changing the Original Array
0
#1

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

0 Likes

#2

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

#3

Of course - thank you!

0 Likes

#4

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

#5

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);

0 Likes

#6

Guys you don’t read the instructions

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

1 Like

#7

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

1 Like

#8

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);

0 Likes

#9

Here is my code

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

return [].concat(array)

}
nonMutatingSort(globalArray);
``````
0 Likes

closed #10
0 Likes

#11

@conniepocky, @prasadbakare It is great that you solved the challenge, but instead of posting your full working solution, it is best to stay focused on answering the original poster’s question(s) and help guide them with hints and suggestions to solve their own issues with the challenge.

Please focus on helping other campers with their questions and not just posting “your” full working solution.

Thank you for understanding.

1 Like