-1

How can I push each item in the possibleNumber array twice into the unplacedArray in JavaScript?

Here's my code, but it doesn't work as desired:

var possibleNumbers = [1, 2, 3,  4, 5, 6, 7, 8];
var unplacedArray = [];
for(possibleIndex = 1; possibleIndex <= possibleNumbers.length; possibleIndex++) {
   possibleNumbers[possibleIndex];
   unplacedArray.push(possibleNumbers[possibleIndex]).fill(2);
}
console.log(unplacedArray);
YakovL
  • 7,557
  • 12
  • 62
  • 102
Munir
  • 1
  • 1

4 Answers4

0

You can use "map" and "flat" to achieve this

var possibleNumbers = [1, 2, 3, 4, 5, 6, 7, 8];
var unplacedArray = possibleNumbers.map(d => [d,d]).flat()
console.log(unplacedArray)

// Or directly flatMap()
var possibleNumbers = [1, 2, 3, 4, 5, 6, 7, 8];
var unplacedArray = possibleNumbers.flatMap(d => [d,d])
console.log(unplacedArray)
Nitish Narang
  • 4,124
  • 2
  • 15
  • 22
  • 1
    Why not directly `.flatMap()` ? – Jonas Wilms Nov 02 '18 at 15:45
  • Can use flatMap as well, which is sort of shorthand for this but I generally tend to work with them separately and not practise "flatMap" that's why it does not strike at the first go to me :) Thanks for pointing though. – Nitish Narang Nov 02 '18 at 15:47
0

Somtehing like this?

var possibleNumbers = [1, 2, 3,  4, 5, 6, 7, 8];
var unplacedArray = [...possibleNumbers, ...possibleNumbers];

console.log(unplacedArray)

// [ 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8 ]
omri_saadon
  • 10,193
  • 7
  • 33
  • 58
0

I think what you want is first to use splice to create a second copy of every element into the array, and then to shuffle it, ala the post here: How to randomize (shuffle) a JavaScript array?

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
0

Using reduce as in 'Using the reduce function to return an array' but adding your custom code inside the reduce:

possibleNumbers.reduce((accumulator, number) => {
    accumulator.push(number);
    accumulator.push(number);
    return accumulator
  },
  []
)
ElMesa
  • 928
  • 8
  • 19