1

I want to create an array that has the values from 1 to 13, four times. This final array should have 52 positions and be something like this:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

I already created the array filled with numbers from 1 to 13

let suit = Array.from(new Array(13), (x, index) => index + 1)

And want to push four times the values on this "suit" array to a final array called "deck".

To do this I've tried the following code:

let suit = Array.from(new Array(13), (x, index) => index + 1)
let suitsNumber = 4
let deck = []

for(let i = 0; i < suitsNumber; i++ ) {
   deck.push(suit)
}

The problem is that the resulting array "deck" is a bidimensional array with length four and in each position is the array suit:

[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13],[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]]

Can someone tell why is not working as I expected?

4 Answers4

1

Use deck.push(...suit) instead of deck.push(suit). This will push the individual numbers to the deck array instead of pushing the entirety of suit array to an index of the deck array.

let suit = Array.from(new Array(13), (x, index) => index + 1)
let suitsNumber = 4
let deck = []

for (let i = 0; i < suitsNumber; i++) {
  deck.push(...suit)
}

console.log(deck)
adiga
  • 34,372
  • 9
  • 61
  • 83
1

You could just use concat with spread syntax ... one the main array that contains other 4 sub-arrays.

const result = [].concat(...Array(4).fill(Array.from(Array(13), (_, i) => i + 1)))
console.log(result)

Or you can use flat() method on the array containing other 4 sub-arrays.

const result = Array(4).fill(Array.from(Array(13), (_, i) => i + 1)).flat()
console.log(result)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
1

You can do this way too

const suit = Array.from(new Array(13), (x, index) => index + 1)
const deck = Array.from(new Array(suit.length * 4), (_, index) => suit[index % 13])
Dmitry Reutov
  • 2,995
  • 1
  • 5
  • 20
0

You can create an 2d array, and flatten it with Array.flat():

const suit = Array.from(new Array(13), (x, index) => index + 1)
const suitsNumber = 4
const deck = Array.from(new Array(suitsNumber), () => suit).flat()

console.log(deck)

Or use Array.flatMap() to create the array:

const suit = Array.from(new Array(13), (x, index) => index + 1)
const suitsNumber = 4
const deck = new Array(suitsNumber).fill(null).flatMap(() => suit)

console.log(deck)
Ori Drori
  • 183,571
  • 29
  • 224
  • 209