-2

I came across something strange. Here two variables which store two differents results:

const membersSortedByCurrentStageTotalPoints = teamMembers.sort((a, b) => compareRanking(a,b,currentIndex));
      
const membersSortedByRankingType = teamMembers.sort((a, b) => compare(a, b, "points"))

But when I'm using the variable membersSortedByCurrentStageTotalPoints I get the results of the variable membersSortedByRankingType.

Anyone would know why ?

user13512145
  • 45
  • 1
  • 5
  • `.sort()` mutates the array in place and returns the same array. `membersSortedByCurrentStageTotalPoints` ***is*** `teamMembers`, not just a copy of it. Same with `membersSortedByRankingType`. You have three names for the same array. – VLAZ Jul 05 '21 at 15:17
  • 2
    Related: [Does .sort function change original array?](/q/24074968/4642212), [How can you sort an array without mutating the original array?](/q/9592740/4642212), [Why A and B are equal after sort()?](/q/26262318/4642212). – Sebastian Simon Jul 05 '21 at 15:33

1 Answers1

1

From the MDN documentation for sort:

Return value

The sorted array. Note that the array is sorted in place, and no copy is made.

The two variables both have the same value: A reference to the same array.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335