Need Help Please Explain Me Return a Sorted Array Without Changing the Original Array

Need Help Please Explain Me Return a Sorted Array Without Changing the Original Array
0

#1

Tell us what’s happening:

I know the Problem but what is problem with my code is it right or it’s wrong Please explain me.
after concating the array my result is [ 5, 6, 3, 2, 9, 5, 6, 3, 2, 9 ]
after the sort the array [ 2, 2, 3, 3, 5, 5, 6, 6, 9, 9 ] what exactly do the code

Your code so far


var globalArray = [5, 6, 3, 2, 9];
function nonMutatingSort(arr) {
  // Add your code below this line
let t = arr.concat(globalArray);
  return t.sort((a,b) => a - b);
  
}
  
  // Add your code above this line

nonMutatingSort(globalArray);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/functional-programming/return-a-sorted-array-without-changing-the-original-array


#2

When you run the function, you give the function an argument globalArray.
This argument gets assigned to arr, the parameter of your function.

You now have the global array, globalArray
and the array in the function, arr,
both having the same content.

Now you concat arr with globalArray, that doubles the content,
because both contents are the same.


#3

Can you suggest me what changes needed in my code.


#4

Thank you I got the correct solution

var globalArray = [5, 6, 3, 2, 9];
function nonMutatingSort(arr) {
  // Add your code below this line
  let myArray = [];
  return myArray.concat(arr).sort((a,b) => a - b);
}
  
  // Add your code above this line

nonMutatingSort(globalArray);

//console.log(globalArray);

console.log(nonMutatingSort(globalArray));

#5

Nice! You could also consider Array.prototype.slice: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice