Search code examples
javascriptarraysreactjsobjectecmascript-6

Splice function on an array of objects


I'm doing a react/javascript exercice and i'm having some trouble understanding the use of splice() in it. I have 8 cards, and i need to randomly assign 4 cards to 2 players. Now everything works fine, but i don't understand the [0] at the end of the let randPokemon = hand2.splice(randIndex, 1)[0]; line.

Here is the full code :

import React, { Component } from "react";
import Pokedex from "./Pokedex";

class Pokegame extends Component {
  static defaultProps = {
    pokemon: [
      { id: 4, name: "Charmander", type: "fire", experience: 62 },
      { id: 7, name: "Squirtle", type: "water", experience: 63 },
      { id: 11, name: "Metapod", type: "bug", experience: 72 },
      { id: 12, name: "Butterfree", type: "flying", experience: 178 },
      { id: 25, name: "Pikachu", type: "electric", experience: 112 },
      { id: 39, name: "Jigglypuff", type: "normal", experience: 95 },
      { id: 94, name: "Gengar", type: "poison", experience: 225 },
      { id: 133, name: "Eevee", type: "normal", experience: 65 }
    ]
  };

  render() {
    let hand1 = [];
    let hand2 = [...this.props.pokemon];

    while (hand1.length < hand2.length) {
      let randIndex = Math.floor(Math.random() * hand2.length);
      let randPokemon = hand2.splice(randIndex, 1)[0];
      hand1.push(randPokemon);
    }

    console.log(hand1);
    console.log(hand2);

    return (
      <div className="Pokegame">
        <h1>Pokegame!</h1>
      </div>
    );
  }
}

export default Pokegame;

I understand (correct me if i'm wrong) that the splice() function can take 2 or more arguments : the first one is the index telling what position to add/remove items, the second one is the number of items to add/remove, and the next arguments being the items we want to add (but i don't use it here since i only want to remove the selected item and add it to the first hand).

Now in this case, i'm having trouble to understand how that [0] works or why it's here...


Solution

  • According to MDN the return value of the splice() is array consisting of removed elements from array.

    Return Value

    An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned

    Its just a way to get the removed element of the array. hand2.splice(randIndex, 1) will return the removed elements from array. So in this case there is only 1 element so [0] will get that first element.