1

I currently have two arrays that look like this:

let suits = ['♣', '♦', '♥', '♠'];
let cards = ['A','2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'];

And I want to combine these to contain an array of 52 strings with all possible combinations of cards. E.g.:

['A♣', 'A♦', 'A♥', 'A♠', '2♣' ...]

I know I could write two nested "for loops" and concatonate them, but is there a more efficient way to do this?

Thanks!

bugsyb
  • 4,977
  • 7
  • 28
  • 39
  • Does this answer your question? [How can I create every combination possible for the contents of two arrays?](https://stackoverflow.com/questions/8936610/how-can-i-create-every-combination-possible-for-the-contents-of-two-arrays) – ponury-kostek Mar 24 '21 at 19:14

2 Answers2

4

You could use Array.prototype.flatMap() method.

const suits = ['♣', '♦', '♥', '♠'];
const cards = ['A','2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'];
const ret = cards.flatMap((x) => suits.map((y) => `${x}${y}`));
console.log(ret);
mr hr
  • 2,954
  • 2
  • 8
  • 18
1

you can do that:

const suits = ['♣','♦','♥','♠']
  ,   cards = ['A','2','3','4','5','6','7','8','9','10','J','Q','K']
  ;
const deck = cards.reduce((d,c)=>[...d,...suits.map(s=>s+c)],[])

console.log( deck )
.as-console-wrapper { max-height: 100% !important; top: 0; }

Or:

const deck = Array.from({length:52},(_,i)=>suits[Math.floor(i/13)]+cards[i%13])
Mister Jojo
  • 16,804
  • 3
  • 16
  • 39