Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: Cannot read properties of undefined (reading 'reduce')

Tags:

reactjs

If the function is in a component, then everything works fine. if I take it out separately and export it to a component, then I get an error TypeError: Cannot read properties of undefined (reading 'reduce')

const getAverageScores = (data) => {
    return data.reduce((acc, {value}) => acc + value, 0) / data.length;

}

Help me please

useEffect(() => {
    if (data.length) {
         setAverage(getAverageScores(data))
    }
}, [data])

and I use getAverageScores there

export  const getStandardDeviation = (data) => {
const total = 0;
const averageScore = getAverageScores()
const squaredDeviations = data.reduce((total, data) => {
    const deviation = data && data.value - averageScore;
    const deviationSquared = deviation * deviation;

    return total + deviationSquared;
}, total);

return Math.sqrt(squaredDeviations / data.length);

}

like image 644
your uncle Avatar asked Oct 25 '25 15:10

your uncle


1 Answers

You are calling getAverageScores with undefined.

const averageScore = getAverageScores()

should be

const averageScore = getAverageScores(data)
like image 97
Federkun Avatar answered Oct 27 '25 05:10

Federkun