## DEV Community is a community of 699,510 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

loading...

# Returning a Sorted Array Without Changing the Original Array

Randy Rivera
Once I truly put my mind on something, I won't ever stop.
・1 min read
• A side effect of the `sort` method is that it changes the order of the elements in the original array. In other words, it mutates the array in place. One way to avoid this is to first concatenate an empty array to the one being sorted (remember that `slice` and `concat` return a new array), then run the `sort` method.

• Use the `sort` method in the `nonMutatingSort` function to sort the elements of an array in ascending order. The function should return a new array, and not mutate the `globalArray` variable.
``````var globalArray = [5, 6, 3, 2, 9];
function nonMutatingSort(arr) {
// Only change code below this line

// Only change code above this line
}
nonMutatingSort(globalArray);
``````
• Answer:
``````var globalArray = [5, 6, 3, 2, 9];
function nonMutatingSort(arr) {
let copy = [...arr];
copy.sort((a, b) => {
return a - b;
})
return copy;
}
console.log(nonMutatingSort(globalArray)); will return [2, 3, 5, 6, 9]
``````
• OR
``````var globalArray = [5, 6, 3, 2, 9];
function nonMutatingSort(arr) {
return [].concat(arr).sort(function(a, b) {
return a - b;
});
}
nonMutatingSort(globalArray);
``````
• Code Explanation:
• First we concatenate the array taken in as a parameter to a new empty array.
• Then Use the `sort()` method create a function to sort the new array in ascending order.

Larson, Quincy, editor. “Return a Sorted Array Without Changing the Original Array.” Https://Www.freecodecamp.org/, Class Central, 2014, twitter.com/ossia.