-
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.
Top comments (0)