DEV Community

Randy Rivera
Randy Rivera

Posted on

Returning a Sorted Array Without Changing the Original Array

  • 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);
Enter fullscreen mode Exit fullscreen mode
  • 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]
Enter fullscreen mode Exit fullscreen mode
  • OR
var globalArray = [5, 6, 3, 2, 9];
function nonMutatingSort(arr) {
  return [].concat(arr).sort(function(a, b) {
    return a - b;
  });
}
nonMutatingSort(globalArray);
Enter fullscreen mode Exit fullscreen mode
  • 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)