Functional Programming: Return a Sorted Array Without Changing the Original Array

What is the reason why I am getting undefined in nonMutatingSort at the end?

var globalArray = [5, 6, 3, 2, 9];

function nonMutatingSort(arr) {

  // Only change code below this line

      

      let newArr= globalArray.sort(function(a, b){

               

              return (a-b)

               

      })

      //console.log(newArr)

  // Only change code above this line

}

nonMutatingSort(globalArray);

Via the instructions:

One way to avoid [mutating the original array] 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.

You need to make a copy of the original array, and then call sort on the copy. You’ve called sort directly on the original array, which mutates it.

You can copy an array several ways

const copy = arr.slice(); // slice
const copy = [...arr]; // spread operator
const copy = arr.concat(); // concat

// you can even use a for loop
const copy = [];
for (const element of arr) {
  copy.push(element);
}
2 Likes

One more thing. Using globalArray here is a big no-no in functional programming. From the first lesson in the Functional Programming section (emphasis mine):

Functional programming is about:

  1. Isolated functions - there is no dependence on the state of the program, which includes global variables that are subject to change

  2. Pure functions - the same input always gives the same output

  3. Functions with limited side effects - any changes, or mutations, to the state of the program outside the function are carefully controlled

Instead, you should reference the arr argument, the input to your function.

2 Likes

I am thankful for your time. Thanks!

var globalArray = [5, 6, 3, 2, 9];

function nonMutatingSort(arr) {

  // Only change code below this line

let newArr=arr.slice()

let emptyArr=[];

let concantenatedArr=emptyArr.concat(...newArr)

console.log(concantenatedArr)

     //console.log(concantenatedArr)

newArr.sort(function(a, b) {

  return a - b;

});

  // Only change code above this line

}

nonMutatingSort(globalArray);

What is the reason why this is not working? It is an solated function and concantenate an empty array with the one wich is being sorted (…new Arr)

What are you returning from the nonMutatingSort function?

1 Like

I noted this. Thanks for your time @bbsmooth and @colinthornton

var globalArray = [5, 6, 3, 2, 9];
function nonMutatingSort(arr) {
// Only change code below this line
let newArr=arr.slice()
let emptyArr=[];
let concantenatedArr=emptyArr.concat(...newArr)
//console.log(concantenatedArr)
   
let sortedArr=newArr.sort(function(a, b) {

return a - b;

});

return sortedArr;


// Only change code above this line
}


nonMutatingSort(globalArray);