#Math on array.map function with rendered items props
1 messages · Page 1 of 1 (latest)
Based on the provided extracts, it seems you're trying to sum a property from each item in an array using the map function in a server-side rendered Next.js application. However, it's important to note that the map function is not the best choice for this operation. The map function is used to create a new array with the results of calling a provided function on every element in the array. It's not designed to return a single output value from an array, which is what you're trying to do.
Instead, you should use the reduce function, which is specifically designed to apply a function against an accumulator and each element in the array (from left to right) to reduce it to a single output value.
Here's how you can use reduce to sum the online property from each players object in your data array:
const totalPlayers = data.reduce((total, server) => total + (server.data.players?.online || 0), 0);
This code will add the online property from each players object in your data array to a total accumulator, which starts at 0. If server.data.players?.online is undefined, it will add 0 instead to avoid NaN errors.
Please note that this code should be placed outside of the Servers component to avoid unnecessary computations on each render.