I am trying to create a deck of 52 cards. I can create it easily with double for-loop but it has O(n2) complexity. So I was trying to play with map() and forEach() array methods but things are complex with them needing to return stuffs. Here is my code below.
(function deckCreate() {
var values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
var suits = ["clubs", "diamonds", "hearts", "spades"];
var newDeck = values.map(function(xValue) {
suits.forEach(function(xSuit) {
return [xSuit,xValue];
});
});
return newDeck;
}());
It gives an array of length 13 all undefined inside. I tried swapping forEach() before map() just incase but the result was the same.
The issue I found while console.log() inside those functions was that the elements were not being mapped to each other but were printed all separately. What could be the issue be?
undefinedbecause.forEachdoesn't return anything. Change that to.mapand put areturnat the beginning of that line and it should work correctly. As far as performance I'd be surprised if this took more than 1ms.