0

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!

1

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

Comments

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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.