What is the best way to calculate the total of values in a JavaScript object?

In my array, I have a list of items with prices that I am attempting to sum up. Here is how it appears in the Chrome developer tools:

(3) [{…}, {…}, {…}]0: {ID: 1, ProductName: " New phone 1", Price: "€ 600"}1: {ID: 3, ProductName: " New phone 2", Price: "€ 1000"}2: {ID: 4, ProductName: " New phone 3", Price: "€ 400"}length: 3__proto__: Array(0)

I want to extract the prices for each item and calculate the total sum of all values. The number of items can vary as they are fetched from an API. Currently, this is how I am accessing the prices:

function setTotalPrice() {
    fetch("http://localhost:1234/api/Product")
        .then(response=>response.json())
        .then(data => {
            data.forEach(element => {
                console.log(element.Price)
            });
        })
}

Answer №1

To extract the numbers from the Price string, you can use the split method and then sum them up using the reduce function.

const data = [
    { ID: 1, ProductName: 'New phone 1', Price: '€ 600' },
    { ID: 3, ProductName: 'New phone 2', Price: '€ 1000' },
    { ID: 4, ProductName: 'New phone 3', Price: '€ 400' },
];

const result = data.reduce((acc, val) => acc + parseInt(val.Price.split(' ')[1], 10), 0);

console.log(result);
console.log('€ ' + result);
If the API returns a floating point number for the Price, make sure to use parseFloat instead:
const data = [
    { ID: 1, ProductName: 'New phone 1', Price: '€ 600.25' },
    { ID: 3, ProductName: 'New phone 2', Price: '€ 1000' },
    { ID: 4, ProductName: 'New phone 3', Price: '€ 400.10' },
];

const result = data.reduce((acc, val) => acc + parseFloat(val.Price.split(' ')[1]), 0);

console.log(result);
console.log('€ ' + result);

Answer №2

let total = items
  .map(({ cost }) => {
    const startIndex = cost.substring(cost.lastIndexOf(' ') + 1);
    return parseFloat(startIndex, 10)
  })
  .reduce((x, y) => x + y, 0)
console.log(`Total Cost: $ ${total}`)

Answer №3

A great way to calculate the sum of prices using JavaScript is by utilizing the reduce method along with a regular expression like /\d+/

let data = [
    { id: 1, product: 'phone 1', price: '€ 400' },
    { id: 3, product: 'phone 2', price: '€ 3000' },
    { id: 4, product: 'phone 3', price: '€ 600' },
];

let sum = data.reduce((a,{price}) => a + Number(price.match(/\d+/)),0);

console.log(sum);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Turn off and then turn on user input without exiting the textarea

I've been working on a small project that requires me to enable and disable text input in a textarea using key commands, similar to Vi/Vim's insertion and command modes. However, I'm struggling to find an elegant solution. Disabling the tex ...

Display various v-dialog boxes with distinct contents in a vue.js environment

Hello there! I am currently working on customizing a Vue.js template and I have encountered an issue with displaying dynamic v-dialogs using a looping statement. Currently, the dialog shows all at once instead of individually. Here is the structure of my ...

After making changes to the variables in my forEach loop, they revert back to their initial values

I have been attempting to create a query to retrieve all earnings and withdrawal amounts and then sum them up. However, I have encountered an issue where, after the forEach loop finishes and exits, the updated values stored in a variable revert back to t ...

Exploring Uncharted Territory: Defining Array Bounds and Iterating through

My current struggle lies within the boundaries of an array as I work with 3 different worksheets. In the first two sheets, I convert information into arrays (referred to as array1 and array2) and perform calculations between them to generate a third array. ...

What is the best way to destructure an array enclosed within the Promise keyword in JavaScript?

Currently, I am attempting to extract information from a PSQL table using the following code: async function requestData() { var selectQuery = `SELECT "fName", "lName", "phoneNumber", "eMail" FROM public."Use ...

Transferring values between arrays in PHP: A step-by-step guide

For instance: $item = Array( [0] => Array( [id]="1" [file]="new" ) [1] => Array( [id]="2" [file]="sample" ) [2] => Array( [id]="3" [file]="hello" ) [3] => Array( [id]="4" [file]="garden" ) [4] => Array( [id]="5" [file]="door" ) [5] => Ar ...

Form featuring a mandatory checkbox that must be selected in order to proceed; failure to do so will result in an

So here’s the situation: I have a form with a checkbox for agreeing to the terms of service, and I want to make sure it is checked before proceeding with the donation process. I only have the HTML code and no idea how to implement this functionality. Ide ...

Converting an unordered list into a <select> dropdown with jquery - a step-by-step guide

Can you help me transform an unordered list that looks like this? <ul class="selectdropdown"> <li><a href="one.html" target="_blank">one</a></li> <li><a href="two.html" target="_blank">two</a></ ...

Exploring the creation of a WebGL viewer by utilizing Three.js in conjunction with ColladaLoader.js

I am in the process of setting up a WebGl viewer using three.js + colladaloader.js, but I'm encountering some difficulties when attempting to import and visualize my own collada object. The example loads correctly, however, when I try to incorporate m ...

JavaScript Discord Bot Unresponsive to Commands

I'm currently working on setting up my first discord bot from a github repository. It successfully connects to discord and logs into the server, but it's not responding to !help commands or any other commands for that matter. The code for the com ...

Discover the smallest 'duo' within a collection

I am dealing with an array composed of 'array pairs': [[time, distance], [time, distance], [time, distance], [time, distance], ...] My goal is to locate the index of the 'pair' with the minimum time. In cases where there are multiple ...

An issue with array segmentation causing a fault in C programming

Looking to create a program that initializes an integer array with a size of 987654321 for storing values of 1 and 0 only. Here is the code snippet: #include <stdio.h> #include <stdlib.h> int main(){ int x, y, z; int limit = 987654321 ...

Managing HTML5 Video in a slider

I've designed a unique video slider that cycles through 4 videos. Each video has a custom play button and additional overlay content. Once the video starts playing, the overlay content and play button fade out to reveal the default video controls. The ...

Javascript prototype issue - Variable stays undefined

Check out the following code snippet: function Person(first, last, age, eyecolor) { this.firstName = first; this.lastName = last; this.age = age; this.eyeColor = eyecolor; } var person=new Person("MyName","MySirname",14,"B ...

Encountering a parsing issue within my React program

I keep encountering a parsing error while trying to run my React application The compilation fails with the following error message: ./src/App.js Line 7: Parsing error: Unexpected token, expected "{" After reviewing my code, I couldn't find any unex ...

Managing webdriver.io timeouts

What I'm trying to achieve is: Determine if the element "Error" span exists then perform a specific action if it does === else check if element "el2" span exists then take another action ==== else perform a default action This is my ...

Populate a database with information stored in an array using Codeigniter

I am trying to insert data from an array into a database using the CodeIgniter framework. The array format is as follows: Array ( [run_date] => Array ( [0] => 2015-06-15 11:10 [1] => 2015-06-15 11:10 [2] => 2015-06-15 11:10 [3] => 2015-06-1 ...

Steps to develop a countdown timer for every iteration of sending an API request using a specified list

Recently, I encountered a challenge with my JavaScript array that holds 40 items. My goal was to develop a function capable of cycling through each item in the array and initiating an API call based on the current value. The caveat here is that I needed a ...

Obtain the parameters of a JavaScript function that is stored as a string

While parsing a webpage, I came across a JavaScript function stored as a string: "translate(737.4170532226562,136.14541625976562)" My goal is to extract the two parameters from this function. I currently parse the string up to the '(' and &apos ...

How can one effectively manage irregularly nested object/arrays within a Meteor framework?

Having difficulty finding a smart and effective method to manage nested arrays/objects with varying dimensions in nodeJS. These irregular arrays/objects can have 1, 2, 3, or more dimensions. For instance, consider these 2 different scenarios : Scenario 1 ...