Calculate the total sum of the properties of the objects within the array

I need to calculate the total sum of unit prices. Any suggestions on how I can achieve this?

This is what the array looks like:

 $scope.items = [
    {
        id: '1',
        name: 'Phone',
        quantity: '1',
        unit_price: '200'
    },
    {
        id: '2',
        name: 'IPhone',
        quantity: '1',
        unit_price: '240'
    }
];

Answer №1

Utilize the method reduce on the array below:

let sum = $scope.items.reduce((accumulator, currentValue) => accumulator + parseInt(currentValue.unit_price), 0);

Answer №2

Give this a shot:

let total = 0;
angular.forEach($scope.items, (value, key) => {
    total += value.unit_price;
});

Answer №3

While it is technically possible to utilize reduce in this scenario, there is really no need for it and the chances of making mistakes are high. (reduce is more appropriate for advanced functional programming with predefined reducers, otherwise, it just adds unnecessary complexity.)

A straightforward loop will suffice, possibly incorporating some destructuring:

let total = 0;
for (const {unit_price} of $scope.items) {
    total += +unit_price;
//         ^−−−−−−−−−−− converting strings to numbers
}

Check out this live example:

const $scope = {};
$scope.items = [
    {
        id: '1',
        name: 'Laptop',
        quantity: '2',
        unit_price: '800'
    },
    {
        id: '2',
        name: 'Tablet',
        quantity: '1',
        unit_price: '400'
    }
];

let total = 0;
for (const {unit_price} of $scope.items) {
    total += +unit_price;
}

console.log(total);

When transforming your unit_price strings into numbers: my solution here outlines different approaches along with their pros and cons. I have utilized the unary + above, but alternate methods exist.

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

Is there a method to have JavaScript display all the information during a SQL while loop?

I'm currently working on implementing a timer for my script. However, I am facing an issue where the timer only counts down from the last result instead of each individual result returned from the query. Any assistance with resolving this problem woul ...

Integrating individual front end JavaScript files into an Express.js application

I've been working on a JavaScript file that contains over 200 lines of code for the front end logic of my project. It handles interactions like button clicks, image displays, and more, similar to a game. However, I'm struggling to figure out how ...

Cease the ongoing Ajax request and switch to a new Ajax call immediately

Within this code snippet, I am capturing user input for typing and then searching it in a database. However, with each character entered by the user, a new AJAX request is triggered without canceling the previous one. My objective is to have the search fu ...

Re-executing PHP script using AJAX on the existing webpage

I am facing a rather intricate issue. Currently, I am in the process of constructing a page that searches tags in a MySQL table and displays results without any reloading or redirection. The tags are user-input and managed using JavaScript. Let me outline ...

How can I send a variable to a service using AngularJS?

I am currently working on developing an app for movie tracking, and I am fairly new to Angular. I am facing a challenge in passing a variable to this service. Instead of hardcoding the URL, I want it to be a variable. What is the best approach to achieve ...

"Implementing a Texture as Material in Three.js: Step-by-Step Guide

I recently discovered Three.js and I'm really enjoying it. As a newcomer to JavaScript, I'm eager to delve deeper into animation and related topics. //UPDATE I've been working on this code snippet, but unfortunately, it's not functioni ...

What are the benefits of ensuring my Redux store is serializable?

While going through the redux documentation, I came across this important point: Still, you should do your best to keep the state serializable. Don't put anything inside it that you can't easily turn into JSON. This got me thinking, what are t ...

Creating a Blob in JavaScript to Save an Image File (Using the HTML5 File API)

Currently, I am working on a project involving a Chrome extension that involves copying user-selected files into the extension's filesystem. Everything seems to be functioning without any errors, but when attempting to view the image, it appears broke ...

Finding and removing the replicated keys within a JSON array while also retrieving the corresponding JSON path

I have a JSON object that looks like this: {"response":{"result":{"Leads":{"row":[{"LEADID":"849730000000063017","SMOWNERID":"849730000000061001"},{"LEADID":"849730000000063015","SMOWNERID":"849730000000061001","HIII":"hello"},{"LEADID":"84973000000006 ...

JavaScript Array Objects

As a newcomer to the world of Javascript, I've decided to take on the challenge of creating a blackjack game. Utilizing arrays and objects for my game: card = {}, //each card is represented as an object with suit, number, and points properties playe ...

Angular app - static List mysteriously clears out upon refresh

My goal is to create a login page using Angular. I have an Angular component with HTML, CSS, and TypeScript files that manage this functionality. The HTML file contains two fields (Username and Password) and two buttons (Login and Register). When a user en ...

What is the best way to utilize AngularJS to make an HTTP PUT request while including an ID?

I've successfully developed a Restful API in Python that interacts with my database and a table named groups. Currently, I have scripts for GET & POST operations, and now I'm working on creating a script for PUT to update a group. In the HTML doc ...

Retrieve the contents of a script using JavaScript

I have a script on my webpage that looks like this: <script> window.__INITIAL_STATE__ = {"meReducer":{"me":{"id":1234,"groupId":789,"},},//more code removed}; </script> I am looking to trigger a ...

Using forEach Loop with Promise.all in Node.js

I am seeking a solution for a task where I need to read a directory, copy its contents, and create a new file within that same directory. function createFiles(countryCode) { fs.readdir('./app/data', (err, directories) => { if (err) { ...

Experiencing issues with handling $.json in Ember

I've been experimenting with using $.getJSON in conjunction with Ember.js (specifically, I'm aiming to bypass Ember-Data). Below is the code snippet: App = Ember.Application.Create(); App.Model = Ember.Object.extend({ }); App.Users = App.Mode ...

IntelliJ does not support the use of newlines within Vue.js component templates

While working with Vue.js in IntelliJ IDEA, I encountered a small problem related to defining component templates. The issue is that IntelliJ seems to struggle when the template spans more than one line and attempts to concatenate them together. For examp ...

Mass Translation of Rows in Google Sheets

I'm looking to convert numerous foreign city names into Turkish =GOOGLETRANSLATE(A2:A100; "en"; "tr") However, when I use this formula for B2:B100, it only translates B2. Is there a method to translate all of them at once using a single function? ...

What is the best way to trigger a function in Angular.js using an input checkbox?

I have a collection of objects with switches. How can I trigger a function for each switch, passing the object and the switch as parameters? I attempted to use the "ng-change" directive for my checkboxes, but it seems that the function is not being called ...

Submit button in the contact form fails to refresh upon being clicked

My website features a contact form with mandatory fields that users must fill out. If a user misses a field and is prompted to complete all fields, upon returning to fill everything out and clicking "send," nothing happens. The SEND button becomes unrespo ...

What is the best way to create a filter function that continues past the first false value?

Looking for a solution to successfully filter an array of objects by comparing it to another array through looping over its values. The issue arises when the filter function stops at the first false, preventing the full comparison. Any suggestions on how ...