You can use the reduce :

data.reduce((a,v) =>  a = a + v.prix , 0 )

const data = [
  {title : "One",prix:100},
  {title : "Two",prix:200},
  {title : "Three",prix:300}
]

console.log((data.reduce((a,v) =>  a = a + v.prix , 0 )))

Answer from Vivek Doshi on Stack Overflow
๐ŸŒ
Reddit
reddit.com โ€บ r/reactjs โ€บ how can i find the sum of input values in react from virtualdoms?
r/reactjs on Reddit: How can I find the sum of input values in react from VirtualDOMS?
September 2, 2022 -

So I have a react app that calculates the sum of inputs. It has an add row button (addRow function) to add Input Component that takes the values to be summed. Each Input component has delete (deleteRow) and disable (disableRow) button as well as select operation (+ or -)

Now the problem is that I lifted up the input values from Input to App via calculate but how can I actually sum up all input values?

App.js

import "./App.css";
import React, { useState } from "react";
import Input from "./components/Input";
function App() {   
    const [newRow, setNewRow] = useState([]);   
    const [result, setResult] = useState(0);     
    
    const addRow = (event) => {     
        event.preventDefault();     
        setNewRow((prev) => [...prev, Math.random()]);   
    };   
    const deleteRow = (key) => {     
        let filteredRows = [...newRow];     
        filteredRows = filteredRows.filter((input) => input !== key);
        setNewRow(filteredRows);   
    };   
    const calculate = (result) => {     
        setResult(result);   
    }   
    return (     
        <div className="App"> 
            <div className="calculator"> 
                <h3>React calculator</h3> 
                <button onClick={addRow}>Add row</button> 
                <ul>
                {newRow.map((item) => (
                    <Input 
                        key={item} 
                        myKey={item} 
                        deleteRow={deleteRow} 
                        calculate={calculate} />   
                ))}         
                </ul> 
                <div id="sumID" className="sum-styles">{result}</div> 
            </div> 
        </div>   
);
}  
export default App;

Input.js

import "./Input.css";
import React, { useState, useRef } from "react"; 
 
const Input = (props) => {   
    const inputRef = useRef();   
    const selectRef = useRef();    
    const [numbers, setNumbers] = useState({ 
            operator: "",     
            number: "",   
    });    
    
    const disableRow = () => {     i
        nputRef.current.disabled = "true";   
    };   

    const inputHandler = (event) => {     
        event.preventDefault();     
        selectHandler();     
        setNumbers((prev) => {       
            return {         
            ...prev,         
            number: event.target.value,       
            };     
        });     
    props.calculate(Object.values(numbers));   
    };    
    const selectHandler = () => {     
        const operatorVal = selectRef.current.value; 
        setNumbers((prev) => {       
            return {         
                ...prev,         
                operator: operatorVal,       
            };
        });
    };   
return (     
    <li className="item">     
        <select 
            className="select__operator" 
            ref={selectRef} 
            onChange={selectHandler}> 
            <option value="+">+</option> 
            <option value="-">-</option> 
        </select> 
        <div> 
            <span className="num">{Object.values(numbers)}</span> 
            <input                                  
                type="text" 
                ref={inputRef} 
                name="number" 
                placeholder="Enter your number here..." 
                className="input__number" 
                onChange={inputHandler}/> 
        </div> 
        <button onClick={() => props.deleteRow(props.myKey)}>Delete</button> 
        <button onClick={disableRow}>Disable</button> 
    </li>   
); }; 
export default Input;
Discussions

How to display sum of the values entered in input box in react.js?
I want to display sum of the values entered in front of my label dynamically, it should added automatically, For eg: You can see the below image for referenceThis should be the output I have set the More on stackoverflow.com
๐ŸŒ stackoverflow.com
typescript - ReactJs calculate sum of all values present in Table column - Stack Overflow
I am having a Bootstrap-table rendering values from service called in componentDidMount(). Example of my table - Col1 Col2 Col3 1 2 3 4 5 6 7 8 9 More on stackoverflow.com
๐ŸŒ stackoverflow.com
July 4, 2020
Displaying the Sum of values in React JSX
Communities for your favorite technologies. Explore all Collectives ยท Ask questions, find answers and collaborate at work with Stack Overflow for Teams More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to calculate the total sum from numbers in textarea?
Without a description of your problem, it's a bit difficult to help. One thing that might be fooling your debugging efforts is that "state" is not immediately readable after "setState()". Call your test() function directly in the function body instead of the handler. More on reddit.com
๐ŸŒ r/reactjs
4
3
August 27, 2019
Top answer
1 of 1
1

I think that here you are missing a concept of React. You should keep your state high in your hierarchy of components if you need it below.

In this example, you have something in a component Main that you need in a sibling component Header. This means that you should have a parent component that pass this information down to them.

For instance, you can have an App component which somehow takes the JSON and keep it into his state alongside other product information:

// App.js
import React, { Component } from 'react'
import PRODUCTS from '../plist.json'

class App extends Component {

  state = {
    // here we are preparing the state copying all the
    // information of a product plus a quantity property set to 0
    products: PRODUCTS.map(p => ({ ...p, quantity: 0 }))
  }

  render() {
    return (
      <>
        {/* here we should render the two components who needs data */}
        <Footer />
      </>
    )
  }

}

In the render method we can render the three initial components but with some changes...

First, the Header requires the total quantity and the total price. One of React best practices tells us that everything that can be computed from the state, should be outside of it. In this case, we don't need to save these two quantities in the state, because we can easily compute them:

// in App class definition

...

totalQuantity = () =>
  this.state.products.reduce(
    (sum, product) => sum + product.quantity,
    0
  )

totalPrice = () =>
  this.state.products.reduce(
    (sum, product) => sum + product.quantity * product.price,
    0
  )

...

Being able to compute those values, we add the rendering of the Header component to the render method of App:

// in App class definition

...

render() {
  return (
    <>
      <Header quantity={ this.totalQuantity() } 
              price={ this.totalPrice() }
      />
      {/* here we should render the Main component */}
      <Footer />
    </>
  )
}

...

Of course you'll have to change the way you render these values in the Header component:

// Header component, render() method
// remember to apply some formatting for currency etc.
<span className={ this.getClass() }>
  Total Quantity: { this.props.quantity }
  Total Price: { this.props.price } 
</span>

Now, let's rethink a bit the Main component. It does two things:

  • render the products list;
  • handle increment/decrement of quantities;

Let's add Main to the render method and then work on these features:

// in App class definition

...

render() {
  return (
    <>
      <Header quantity={ this.totalQuantity() } 
              price={ this.totalPrice() }
      />
      <Main products={ this.state.products }
            onIncrement={ this.handleIncrement }
            onDecrement={ this.handleDecrement }
      />
      {/* here we should render the Footer component */}
    </>
  )
}

...

In the Main component we need to change the way we render the products because we don't read the JSON anymore, but we can use the data provided by App. In addition, we need to be able to pass increment and decrement events:

// Main

...

render() { return ( { this.props.products.map( (product, index) => this.props.onIncrement(index) } onDecrement={ () => this.props.onDecrement(index) } /> ) } ) }

...

Down in the Product component, we now don't need internal state anymore, because everything we need is provided as props, so it can be a stateless component:

const Product = ({
  image, 
  url, 
  name, 
  price, 
  description, 
  onIncrement, 
  quantity,
  onDecrement
}) => (
  <div className="col-md-4 ml-auto">
    <img className="productpic" 
         src={ require(`./images/${image}`) }
         alt="Product"
    />
    <h2 className="display-6">
      <a href="{url}">
        { name }
      </a>
    </h2>
    <p className="h5 price">
      { price }
    </p>
    <p className="info">
      { description }
    </p>
    <div className="counter">
      <button className="btn btn-info"
              onClick={ onIncrement }>
        +
      </button>
      <div className="count">
        { quantity }
      </div>
      <button className="btn btn-info"
              onClick={ onDecrement }>
        -
      </button>
    </div>
  </div>
)

To complete this behaviour, we need to handle the increment and decrement in the App component, in order to update the state and propagate updated information to Header (quantity and total) and Main.

// in App

...

handleIncrement = index =>
  this.setState(prevState => ({
    products: [
       ...prevState.products,
       [index]: {
          ...prevState.products[index],
          quantity: prevState.products[index].quantity + 1
       }
    ]
  }))

handleDecrement = index =>
  this.setState(prevState => ({
    products: [
       ...prevState.products,
       [index]: {
          ...prevState.products[index],
          quantity: prevState.products[index].quantity - 1
       }
    ]
  }))

...

We're almost done, in your index.js, render just the App component:

import React from "react";
import ReactDOM from "react-dom";
import App from "./components/app";
import './index.css';
import 'bootstrap/dist/css/bootstrap.css';


ReactDOM.render(<App />, document.getElementById("root"));
๐ŸŒ
Reactgo
reactgo.com โ€บ home โ€บ how to find the sum of numbers in an array javascript
How to find the sum of numbers in an array Javascript | Reactgo
November 11, 2023 - let arr = [1,2,3,4,5]; let sum = 0; for (let num of arr){ sum = sum + num } console.log(sum) // 15
๐ŸŒ
DEV Community
dev.to โ€บ this_mkhy โ€บ week-6-sum-two-numbers-app-1800
Week 6 - Sum Two Numbers App - DEV Community
May 31, 2022 - Create a state that holds the summation value with an initial value equal to zero. Create a calculate function that calculates and updates the summation.
๐ŸŒ
Cloudhadoop
cloudhadoop.com โ€บ home
How to sum an array of objects with numbers in react
December 31, 2023 - Reactjs ยท It is a short tutorial on how to get a sum of numbers in React application. It also includes how to calculate sum or numeric properties of an object array with example. Letโ€™s consider the array of objects as given below.
๐ŸŒ
CodePen
codepen.io โ€บ tfbrown โ€บ pen โ€บ zjXvZy
React Numeric Input Sum Calculator
HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents and you could write a loop in Pug ยท Learn more ยท Versions
Find elsewhere
๐ŸŒ
CodePen
codepen.io โ€บ PiotrBerebecki โ€บ pen โ€บ zKEQgL
React JS Sum properties of object
// http://stackoverflow.com/questions/39828497/sum-of-string-values-on-array-object/ console.clear(); let array = [ {quantity: 1, amount: "24.99"}, {quantity: 5, amount: "4.99"} ] function sumProperty(arr, type) { return arr.reduce((total, obj) => { if (typeof obj[type] === 'string') { return total + Number(obj[type]); } return total + obj[type]; }, 0); } let totalAmount = ( sumProperty(array, 'amount') ).toFixed(2); console.log( totalAmount ); // 29.98 let totalQuantity = sumProperty(array, 'quantity'); console.log( totalQuantity ); // 6
Top answer
1 of 2
1

I would get the sum using reduce:

const SumValue = this.state.value && this.state.value.reduce((a, v) => a + v, 0)
2 of 2
0
1) initial columnNames and array list

state = {
    callList: [],
    columnModel: [
       { columnName: "date" },
       { columnName: "totalCalls" },
       { columnName: "answeredCalls" },
       { columnName: "abandonedCalls" },
       { columnName: "abandonRate" },
       { columnName: "avgAnswerSpeed" },
    ]

};

2) Get data from api and prepare array data

try {
    const { errors, list, success } = (await apiService.getCalls(request)).data;
    if (success) {

        // first list is normal numbers count only, 
        // if you want count avg sum for some columns send second param array list and include column names
        // now i want count avg for 'abandonRate', 'avgAnswerSpeed' , others just count sum

        this.setState({ 
            callList: list,
            callListSum: this.sumCount(
                list, 
                ['abandonRate', 'avgAnswerSpeed']
            )
        })
    }
} catch (error) {
    console.log(error);
}

sumCount = (list = [], avgColumns = []) => {
    const sum = {};

    // count numbers
    list.map((item) => {
        Object.entries(item).map(([key, val]) => {
            if (typeof (val) === 'number') {
                sum[key] = sum[key] ? (sum[key] + val) : val;
            }
        })
    });
    
    // count avg
    avgColumns.map(key => {
        if (sum[key]) {
            sum[key] = sum[key] / list.length;
        }
    })
    return sum;
}


3) Render data

<table>
    <thead>
        <tr style={{ backgroundColor: "#F5F7FA" }}>
            {
                this.state.columnModel.map((item, i) =>
                  <th key={i}> {item.columnName}</th>
                )
            }
        </tr>
    </thead>
    <tbody>
        {
            this.state.callList.map(
            (info, index) => (
                <tr
                    key={index}
                >
                    {
                        this.state.columnModel.map((item, i) =>
                           (
                            <td key={i}>
                              {info[item.columnName]}
                            </td>
                           )
                        )
                    }
                </tr>
            )
        )}
        {/* Render sum area */}
        <tr 
            style={{ backgroundColor: "#F5F7FA" }}
        >
            {
                this.state.columnModel.map((item, i) =>
                    (
                        <td style={{ fontWeight: "bold" }} >
                         {this.state.callListSum[item.columnName]}
                        </td>
                    )
                )
            }
        </tr>
    </tbody>
</table>
๐ŸŒ
YouTube
youtube.com โ€บ ilmyst
How to Calculate Sum of Product Price - Javascript/ReactJs - Part 1 - YouTube
How to Calculate Sum of Product Price - Javascript/ReactJs - Part 1
Published ย  October 2, 2022
Views ย  412
๐ŸŒ
Font Awesome
fontawesomeicons.com โ€บ fa โ€บ react-js-sum-of-all-items-in-a-array
React Sum Values in Array of Objects: Sum Array Values, Sum Array of Numbers,Add All Numbers in Array
It accumulates the sum by adding each element to an accumulator (acc), beginning with an initial value of 0. The final sum variable contains the total sum of the array's numbers, offering a cleaner and more efficient approach. ... If you prefer to use a for loop, you can iterate through the ...
๐ŸŒ
Reddit
reddit.com โ€บ r/reactjs โ€บ how to calculate the total sum from numbers in textarea?
r/reactjs on Reddit: How to calculate the total sum from numbers in textarea?
August 27, 2019 -

I have a textarea of type text and I want to check if I have numbers and calculate the total value and show it to another input of type number. Here is what I have tried so far:

const [state, setState] = useState({ price: "", items: "" });

const handleInputChange = event => { setState({ ...state, [event.target.name]: event.target.value }); testvalues() };

const calculatValues = () => { let total = 0; const str = state.items const regex = /[+-]?([0-9]*[.,])?[0-9]+/g; const m = regex.exec(str)

while (m !== null) {
  // This is necessary to avoid infinite loops with zero-width matches
  if (m.index === regex.lastIndex) {
    regex.lastIndex++;
  }
  m[0] = m[0].replace(',', '.');

  total = total + parseFloat(m[0]);
}

setState({ ...state, price: total.toFixed(2) });

}

const testvalues = () => { let sum; if (state.items) { sum = state.items.match(/[0-9.]+/g).reduce((acc, curr) => { const number = +acc + Number(curr) return number }, 0) } console.log(sum) }

๐ŸŒ
freeCodeCamp
forum.freecodecamp.org โ€บ javascript
Dynamically Calculate Input values - React - JavaScript
December 16, 2020 - Hello , I am working on a form that is filled by the user and should update other input fields at the same time according to the entered data. For instance, If we have 3 input fields of number 1, number 2 and their sum.โ€ฆ