Search code examples
javascriptarrayspushsplice

Pushing spliced items returns nested array


I am trying to push 3 random items from an array into a new array. I use splice() to grab an item and remove it from the old array. When I push() the items, I would like to get them back in a single array.

For example:

["b", "f", "a"]

This is my code:

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 seems like I am pushing the spliced items as arrays into the new array, is there a way to fix this?

[
  [
    "b"
  ],
  [
    "f"
  ],
  [
    "a"
  ]
]

Solution

  • You could spread ... the array from Array#splice.

    Or take the first element with and index.

    letters.splice(Math.floor(Math.random() * letters.length)[0]
    

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