To find the sum of an array of numbers in React, you can use the reduce()
method, which iterates through the array and accumulates the sum. Here’s how you can do it:
import React from 'react';
function SumOfArray() {
const numbers = [5, 10, 15, 20, 25];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
return (
<div>
<p>Numbers: {numbers.join(', ')}</p>
<p>Sum: {sum}</p>
</div>
);
}
export default SumOfArray;
In this example, the SumOfArray
component calculates the sum of the numbers
array using the reduce()
method. The reduce()
method takes a callback function as its first argument, which is called for each element in the array. The accumulator
accumulates the sum, and the currentValue
is the current element being processed. The second argument of reduce()
is the initial value of the accumulator
, which is set to 0 in this case.
Replace [5, 10, 15, 20, 25]
with your own array of numbers, and the component will display both the array and the sum of its elements.
The reduce()
method is a powerful tool for many array operations, so it’s useful to learn and understand how it works.