skip to Main Content
import React from 'react';
import ReactDOM from 'react-dom';
import { useState } from 'react';

const Dice = () => {
    const [dice, setDice] = useState([1, 1, 2, 2]);

    function rollDice() {
        return Array.from({length: 4}, () => Math.floor(Math.random() * 6) + 1);
    }


    const handleClick = () => {
        setDice(rollDice());
    }

    const rolls = dice.map(die => <span> {die} </span> );

    const stat = dice.splice(Math.min(...dice)).reduce(function(a, b) {
        return a + b;
    });

    return (
        <>
            <button onClick={handleClick}>Roll for stats</button>

            <div>
                Your rolls are: {rolls}
            </div>
            
            <div>
                Your stat is: {stat}
            </div>
        </>
    );
}

export default Dice;

if (document.getElementById('dice')) {
    ReactDOM.render(<Dice />, document.getElementById('dice'));
}

So I’m making online DnD and I’m testing out the dice rolls for stats, first few iterations went fine and then it returned the sum of the wrong numbers, it "randomly" removes the numbers I need and returns the wrong sum. I am doing this after being away from the code world for awhile so I’m sorry if it’s something dumb but i really can’t figure out what’s the issue.

3

Answers


  1. Chosen as BEST ANSWER

    This does the trick, changing stat to a function and running the splice method on a copy of the dice array:

    const stat = () => {
        let smallestRoll = Math.min(...dice)
        let indexOfSmallest = dice.indexOf(smallestRoll)
        let diceCopy = [...dice]
    
        diceCopy.splice(indexOfSmallest, 1)
    
        let sum = diceCopy.reduce(function(a, b) {
            return a + b;
        });
    
        return sum;
    }
    

    and returning it as a function:

    return (
        <>
            <div>
                Your stat is: {stat()}
            </div>
        </>
    );
    

    Thank you for all your help!


  2. You can use reduce for this

    function sumOfNHighestValues(arr: number[], n: number): number {
      const sortedArr = arr.sort((a, b) => b - a); // sort the array in descending order
      const slicedArr = sortedArr.slice(0, n); // slice the first n elements
      const sum = slicedArr.reduce((total, num) => total + num, 0); // sum the sliced elements
      return sum;
    }
    
    // example usage
    const arr = [5, 2, 8, 3, 9, 4];
    const n = 3;
    const result = sumOfNHighestValues(arr, n);
    console.log(result); // output: 21 (sum of 9, 8, and 5)
    Login or Signup to reply.
  3. you can try es6 syntax, extension operator(…)

    var arr = [22,13,6,55,30];
    console.log(Math.max(...arr)); // 55
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search