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?

The sort method is only going to change the order of the elements (in this case objects) in the array and not the contents of the elements.

You will need to rethink your strategy here. Can I assume this card game is not a normal deck of cards (i.e. there is no such thing as a 1 of hearts)? You could first create an array of objects containing all the combinations of values and suits and then use the Fisher-Yates shuffle algorithm to actual reorder (randomly) the deck of cards if that is what you meant by “reorder” in your original post.

1 Like

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