skip to Main Content

When duplicating an array and using sort(), why do both arrays get sorted?

For example:

c = [2,4,9,1,10];
b = c;
b.sort();
console.log(b+" "+c)

I was expecting the array (c) to remain as [2,4, 9, 1, 10] instead it returns the same as b using sort() with both returning [1, 10, 2, 4, 9]

2

Answers


  1. Yes, sort() changes array "in place" as is stated in docs. You need to make a copy by [...c] or you can use toSorted()

    Login or Signup to reply.
  2. So in this case you are modifying the array in place, pointing to same memory location, you need to create a copy of c array by using a method called array destructuring/sperad operator. i.e b=[…c] and now you can perform sort operation on array b which does not affect array c

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search