Home > Software design >  .map() method not generating a new array from the return function
.map() method not generating a new array from the return function

Time:02-24

In a react challenge where I should create a card that needs to generate an X amount of numbers, where X is an user's input. So I created a function called "getRandomNum" to generate a random number within a range and verifify if the number is already in the array, if so, another number will be generated. Then, I created another function called "generateNumbers" to create an user's input size array, called arrayNumbers, and then used the .map() method using "getRandomNum" as a callback, to insert the non-repeated random numbers in the array, then there's the problem, the array remains the same as before the .map() method. See the code below, please:

import './Megasena.css'
import { useState } from 'react'
 
const getRandomNum = (minParam, maxParam, array) => {
    let min = Math.ceil(minParam)
    let max = Math.floor(maxParam)
    let numGerado = parseInt(Math.floor(Math.random() * (max-min 1))   min)
    
    return array.includes(numGerado) ?
        getRandomNum(minParam, maxParam, array) :
        numGerado
}
 
const generateNumbers = amountOfNumbers => {
    let arrayNumbers = Array(amountOfNumbers).fill(0)
    
    arrayNumbers.map(_ => getRandomNum(1, 99, arrayNumbers))
 
    if (amountOfNumbers <= 40) {
        return (arrayNumbers.map(num => {
            return (
                <li key={num} className="numberItem">{num}</li>
            )
        })
    )}   else {
        return (<p>A quantidade máxima de itens é 40!</p>)
    }
}
 
export default props => {
    const [numberOfItens, setNumberOfItens] = useState(0)
 
    return (
        <div className="megasenaComp">
            <div className="numbersArea">
                <ul className="numbersList">{generateNumbers(numberOfItens)}</ul>
            </div>
            <div className="inputArea">
                <label htmlFor="inputNumItens">Quantidade de Números:</label>
                <input id="inputNumItens" type="text" onChange={e=> {setNumberOfItens( e.target.value)}}
                />
            </div>
        </div>
    )
}

CodePudding user response:

map() will always return new array See this documentation.

So, you should collect the data into a new variable or rewrite the existing variable and then iterate over it.

You can do something like below:

const generateNumbers = amountOfNumbers => {
  let arrayNumbers = Array(amountOfNumbers).fill(0)

  arrayNumbers = arrayNumbers.map(_ => getRandomNum(1, 99, arrayNumbers))

  if (amountOfNumbers <= 40) {
    return (arrayNumbers.map(num => {
        return (
            <li key={num} className="numberItem">{num}</li>
        )
    })
  )}   else {
    return (<p>A quantidade máxima de itens é 40!</p>)
  }
}
  • Related