简体   繁体   中英

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"
  ]
]

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

You can use the function Array.prototype.concat instead.

 const letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']; let newletters = []; for (let i = 0; i < 3; i++) { newletters = newletters.concat(letters.splice(Math.floor(Math.random() * letters.length), 1)); } console.log(newletters);

 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.flat());

Use the ... operator inside the push statement.

const letters = ['a', 'b', 'c', 'd', 'e'];
const newLetters = []
newLetters.push(...letters.splice(1, 2)) // Equal to newLetters.push('b', 'c')
console.log(newletters)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM