Sorting arrays with slice and sort without concat?

Tell us what’s happening:
Why do we need concat method at all? Can someone help me solving this issue without concat?

  **Your code so far**

var globalArray = [5, 6, 3, 2, 9];
function nonMutatingSort(arr) {
// Only change code below this line
var newArr= globalArray.slice(0,5)
return newArr;


// Only change code above this line
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36

Challenge: Return a Sorted Array Without Changing the Original Array

Link to the challenge:

You don’ t need to use the .concat method, but it is one way to do it.
Calling .slice() on an array without any parameters makes a duplicate of the array. Sorting this new array does not change the original array.

Isn’t easier to use rest operator?

Can you explain what you mean by rest method? If you are referring to the spread operator, then yes, that is another way to do it.

1 Like

you can also use slice with only it’s starting point. .slice(0) will copy the entire array.

See this post, explains every way to copy an array, is pretty handly: How to clone an array in JavaScript

1 Like

Thanks guys! Yes, Jonathan, spread operator was what I had in mind…Gonna work out more on basics :rofl:

Here is part of the challenge description regarding mutation:

One way to avoid this is to first concatenate an empty array to the one being sorted

It only suggest one of the ways you can sort an array, without mutating it, but retruning a new array. Spread, slice etc, are all other valid methods and each one can have its particular use and be more appropriate in a certain situation, so its a good thing to be able to apply each one of them and have them in your arsenal

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.