Search code examples
javascriptarrayssplice

Why is splice not removing elements from my array?


I am creating a roulette game that displays random items from different arrays when the wheel lands on a specific category. So far everything works except when the wheel lands on a category, it selects the same random item from the correct array over and over again. I am trying to use math.random and the splice method to randomly select an item from an array, and remove that item so only new, random items from the array can be displayed after, but it hasn't worked.


Solution

  • I rearranged the input arrays into an array of arrays (5 arrays of 9 elements = 45). I'm guessing that you want the whole thing shuffled.

    const log = data => console.log(JSON.stringify(data));
    
    let zones = [
      ["🎁", "🎆", "🎯", "🌈", "🌛", "💩", "💰", "🍒", "🌴"],
      ["🌞", "🍀", "💀", "💘", "💣", "🎲", "🎰", "🎈", "🗿"],
      ["🎁", "🎆", "🎯", "🌈", "🌛", "💩", "💰", "🍒", "🌴"],
      ["🌞", "🍀", "💀", "💘", "💣", "🎲", "🎰", "🎈", "🗿"],
      ["🎁", "🎆", "🎯", "🌈", "🌛", "💩", "💰", "🍒", "🌴"]
    ];
    let zoneSize = zones.length * zones[0].length;
    let symbolZones = [];
    
    for (let i = zoneSize; i > 0; i--) {
      let deg = zones.flatMap(z => z.splice(Math.floor(Math.random() * z.length), 1));
      if(deg.length > 0) {
        symbolZones.push(deg);
      }
    }
    log(`Original Array zones`);
    log(zones);
    log(`New Array symbolZones`);
    log(symbolZones);
    .as-console-row-code {
      display: block;
      width: 100%;
      overflow-wrap: anywhere;
    }
    
    .as-console-row::after {
      content: ''!important
    }