javaScript: sorting an array with multiple object/properties

Hello every one, I am trying to build a card game using javaScript.
I have used the .sort() method to reorder my deck of cards.

My array is composed by a value: int number and a string: the card’s suit.
I found a function to be included in the sort method (compare function) which should order the numerical part as well as the suit.

The ideal would be an array as follows:

{value : 1, suit: 'hearts'} 
{value : 2,  suit: 'hearts'} 
{value : 3, suit: 'hearts'}
{value : 4, suit: 'hearts'} 
{value : 5,  suit: 'hearts'}  
{value : 1, suit: 'clubs'} 
{ value : 2,  suit: 'clubs'} 
{value : 3, suit: 'clubs'} 
{value : 4, suit: 'clubs'}
{value : 5,  suit: 'clubs'}
etc. ]```

```//sorting code
myCards.sort((a,b) => a.value - b.value || a.suit - b.suit); ```

I  found this method online at (https://stackoverflow.com/questions/13211709/javascript-sort-array-by-multiple-number-fields). This should pass a second property using the `||` operator (I also tried &&).

Unfortunately the result I get is : 

```{value : 1, suit: 'clubs'} 
{value : 1, suit: 'hearts'} 
{ value : 2,  suit: 'clubs'} 
{value : 2,  suit: 'hearts'} 
{value : 3, suit: 'clubs'} 
{value : 3, suit: 'hearts'}
{value : 4, suit: 'clubs'}
{value : 4, suit: 'hearts'} 
{value : 5,  suit: 'clubs'
{value : 5,  suit: 'hearts'}  ```

how can I improve my code?

If you want it to sort suit first and then value you need to flip your OR statement, so you first check suit and then value. Note, that a.suit - b.suit is not how you compare strings. Use a.suit.localeCompare(b.suit) instead.

2 Likes

@snigo this is exactly what I was trying to do, reorder a shuffled array, taking in consideration 2 elements one of them (suit) a string; using localeCompare I was able to use the sort() method.

thanks a lot
Paola