I'm currently working on a script that involves selecting 3 random items from an array and storing them in a new array. To achieve this, I'm utilizing the splice()
method to extract an item from the original array. However, when I attempt to add these items to the new array using push()
, the items are being stored as nested arrays rather than a single array.
Here's an example scenario:
["b", "f", "a"]
This is my current code implementation:
const letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
let newletters = [];
for (let i = 0; i < 3; i++) {
newletters.push(letters.splice(Math.floor(Math.random() * letters.length), 1));
}
console.log(newletters);
It appears that the spliced items are being added to the new array as subarrays. Is there a way to address this issue?
[
[
"b"
],
[
"f"
],
[
"a"
]
]