Returning a Sorted Array Without Changing the Original Array
Randy Rivera
Posted on July 1, 2021
-
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 thatslice
andconcat
return a new array), then run thesort
method.- Use the
sort
method in thenonMutatingSort
function to sort the elements of an array in ascending order. The function should return a new array, and not mutate theglobalArray
variable.
- Use the
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.
💖 💪 🙅 🚩
Randy Rivera
Posted on July 1, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
javascript Functional Programming: Passing Arguments to Avoid External Dependence in a Function
June 21, 2021