Switch out "FOR" in order to sum up every value within an array

Utilizing Javascript, I have an array defined as follows:

counts: [
      { id: 1, value: 0 },
      { id: 2, value: 10 },
      { id: 3, value: 5 },
      { id: 4, value: 3 }
    ]

I aim to calculate a variable named total that holds the sum of all value fields in the counts array. As of now, I am achieving this through:

Total() {
    let total = 0;
    for (let i = 0; i < counts.length; i++) {
      total += counts[i].value;
    }
    return total;   
}

While this method works, there might be a more efficient approach. I attempted to use the reduce method, but I struggled to achieve the desired outcome. How can I go about improving this?

Answer №1

You have the option to incorporate the destructured data using Array#reduce.

let data = { items: [{ id: 1, quantity: 10 }, { id: 2, quantity: 5 }, { id: 3, quantity: 15 }] },
    total = data.items.reduce((result, { quantity }) => result + quantity, 0);

console.log(total);

Answer №2

let  numbers = [
       { id: 1, value: 7 },
       { id: 2, value: 12 },
       { id: 3, value: 6 },
       { id: 4, value: 9 }
     ]
     
 const sum = numbers.map(x => x.value).reduce((a,c) => a +c)
 
 console.log(sum)
     
     

Transform your array to only include the value data and then apply reduce

 const sum = numbers.map(x => x.value).reduce((a,c) => a + c)

Answer №3

If you want to achieve this using reduce, simply set a default value of 0:

counters = [
       { id: 1, value: 0 },
       { id: 2, value: 10 },
       { id: 3, value: 5 },
       { id: 4, value: 3 }
     ]
     
total = counters.reduce((sum, counter) => sum + counter.value, 0);

console.log(total);

Answer №4

If you want to keep it simple, just use the reduce method. You can find more information about it here ;)

const total = counters.reduce((acc, curr) => acc + curr.value, 0);

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

The Vue.js component is only refreshing after I manually refresh the browser page

As a newcomer to Vue.js and other reactive frameworks, I am still learning the ropes. I have a component that needs to update whenever there is a change. The goal is to display a balance from a specific login. <li :key="balance">Balance {{ balance ...

Discover the secret to automatically calling a function every minute when the page is loaded!

Our team is currently developing a PhoneGap application with 4 pages. We are in need of posting the current latitude and longitude every minute to our server. Fortunately, we are familiar with how to post values to the server as well as how to retrieve the ...

JavaScript - Sort an array containing mixed data types into separate arrays based on data

If I have an array such as a=[1,3,4,{roll:3},7,8,{roll:2},9], how can I split it into two arrays with the following elements: b=[1,3,4,7,8,9] c=[{roll:3},{roll:2}]. What is the best way to separate the contents of the array? ...

Utilizing timezones with Moment.js

Currently, I am utilizing momemt.js and moment-timezone.js to present time in the browser. At this time, I have received epoch time from the server which has been converted to central time. My goal now is to exhibit the time in EST/EDT format. To achieve t ...

create a JavaScript array variable for posting items

My goal is to use this javascript to make four posts for the 'var msg' array. However, it currently posts 'encodeURIComponent(msg[i])' four times instead. How can I resolve this issue? var msg = ['one', 'two& ...

Manipulating all components of a specific type in App.vue with VueJS: Is it possible?

Consider this template with FruitPrices as a component: <template> <div id="app"> <div> <span @click=SOME_FUNCTION> Change currency </span> <FruitPrices fruit="apple"></FruitPrice ...

Ways to utilize the map() function with data retrieved from an axios response?

Utilizing axios for data retrieval from the server and then storing it in the state. However, when attempting state.map( post => {console.log(post)} ), no output is displayed. The technologies being used are Express, Mongoose, NextJS, and Axios. My ap ...

detect and handle errors when deploying the Node.js function

I'm currently attempting to use code I found on Github to insert data into a Firestore database, but unfortunately, I keep encountering an error. Here's the specific error message: 21:1 error Expected catch() or return promise/catch-or-re ...

Leveraging Amplify for offline storage while transitioning between HTTP and HTTPS protocols

Recently, I encountered an issue with Amplify 1.0a1 on my website. It seems that when storing the value of prod_id in localStorage on a page using HTTP, and then navigating to a page using HTTPS (such as the 'list' page), I am unable to access th ...

Animate CSS during page load

Currently, I am implementing AJAX to dynamically load pages on my website. During the loading process, I wish to incorporate a spinning animation on the logo to indicate that content is being fetched. The jQuery script (although I'm still learning an ...

Enhancing Navbar Design with Tailwind CSS in NextJS and React

I have not worked with React in a while and just started learning Next.Js. I am trying to figure out how to change the background of my Navbar using Tailwind CSS based on a boolean value "current" (true/false) depending on which page the user is on with Ne ...

The jQuery statements are not properly executing the if and else conditions

i'm currently assessing the condition using this particular code. jQuery(document).ready(function($){ $('#uitkering_funds').hide(); $('#uitkering_funds_hoofd').hide(); $('#partner_uitkering').hide(); $('#par ...

Troubleshooting Display Issue with Nested Div Selection in jQuery Tooltips

I have a long list of data consisting of 30-50 rows, each row needing its own distinct tooltip. Creating unique IDs for each row would require unnecessary JavaScript code. My goal is to utilize jQuery to retrieve the tooltip from the nested <DIV> wit ...

Include a class above the specified element; for instance, apply the class "act" to the "<ul>" element preceding the "li.item1"

Hello there! I need some assistance, kinda like the example here Add class and insert before div. However, what I really want to do is add the class "act" to a class above that matches the one below: Here's how it currently looks: <ul> ...

The image from the local source displays correctly in the initial component without any issues, but it does not appear in its corresponding detail component

My blog has a component for displaying posts and another component for showing the details of a single post as seen below. A key point to note is that while the blog component can load and display images, the blog details component cannot. Why is this? A ...

When using the Ng --version command on a development package, it throws an error

I encounter an error with a development package when cloning a repository. I would greatly appreciate any advice on how to resolve this issue. https://i.stack.imgur.com/DBp5r.png ...

When scrolling, numerous requests are sent to ajax - how can I consolidate them into a single request for lazy loading?

I encountered a problem where multiple Ajax requests are being sent when I try to call an Ajax function after scrolling. How can I resolve this issue? $(window).scroll(function(){ var element = $('.MainChatList'); var scrolled = false; ...

How can one ensure the preservation of array values in React?

I'm struggling to mount a dynamic 'select' component in React due to an issue I encountered. Currently, I am using a 'for' loop to make API calls, but each iteration causes me to lose the previous values stored in the state. Is t ...

Having difficulties accessing the properties of a dynamically created JSON object with ng-repeat functionality

Within an ng-repeat loop, I have implemented a radio button that assigns the entire person object to a scope variable as shown below: <li ng-repeat="person in people"> <label>{{person.name}} <input type="radio" ng-model="$parent.s ...

Is there a method available for troubleshooting unsuccessful AJAX requests? Why might my request be failing?

Whenever I click on a button with the class "member-update-button," an alert pops up saying "got an error, bro." The error callback function is being triggered. Any thoughts on why this might be happening? No errors are showing up in the console. How can I ...