Total the values of specific properties in an array of objects when another property meets a specified criterion

I've been attempting to calculate the total sum of account balances for accounts labeled as "Savings", but my current approach seems to be unsuccessful. My initial plan was to iterate through the array using a forEach loop and then check if the account type is classified as savings, however I'm encountering some issues.

const accounts = [
    {acctNo: 123, type: 'Checking', balance: 150},
    {acctNo: 234, type: 'Checking', balance: 200},
    {acctNo: 345, type: 'Savings', balance: 550},
    {acctNo: 456, type: 'Checking', balance: 550},
    {acctNo: 567, type: 'Savings', balance: 1500}
];
const sum = accounts.forEach(function(account){
  if (account.type === 'Savings'){
    account.reduce(function(a,b){
      return {balance: a.balance + b.balance};
    });
  }
});

console.log(sum);

Answer №1

When using a forEach loop, you are unable to return any values. Additionally, performing a reduce operation directly on accounts may not be the most logical approach. Consider utilizing filter and map methods instead, ensuring that you perform the reduce operation on a list:

accounts.filter(account => account.type === 'Savings')
    .map(account => account.balance)
    .reduce((accumulator, currentValue) => accumulator + currentValue)

Answer №2

Here is a method to achieve this task by combining several array functions:

1) Begin by using the filter function to extract only the accounts categorized as 'Savings'

2) Next, utilize the map function to isolate and gather the account balances

3) Finally, sum up the obtained array values. In this example, I have used the reduce function in conjunction with map and filter. However, you could also accomplish this by manually iterating through the array and keeping track of the total balance if that is your preference

It is worth noting that arrow functions are employed here for succinctness and clarity. Nevertheless, traditional function() { ... } expressions can be substituted without altering functionality.

const accounts = [
    {acctNo: 123, type: 'Checking', balance: 150},
    {acctNo: 234, type: 'Checking', balance: 200},
    {acctNo: 345, type: 'Savings', balance: 550},
    {acctNo: 456, type: 'Checking', balance: 550},
    {acctNo: 567, type: 'Savings', balance: 1500}
];

const sum = accounts.filter(account => account.type === 'Savings')
                    .map(account => account.balance)
                    .reduce((acc, bal) => acc + bal);

console.log(sum)

Answer №3

reduce functions as an array method, not an object method.

Using both forEach and reduce is unnecessary. The reduce method already iterates over the array, simply include the if condition within the function.

const accounts = [
    {acctNo: 123, type: 'Checking', balance: 150},
    {acctNo: 234, type: 'Checking', balance: 200},
    {acctNo: 345, type: 'Savings', balance: 550},
    {acctNo: 456, type: 'Checking', balance: 550},
    {acctNo: 567, type: 'Savings', balance: 1500}
];
const sum = accounts.reduce(function(a, account){
  if (account.type === 'Savings'){
    return a + account.balance;
  } else {
    return a;
  }
}, 0)

console.log(sum)

Answer №4

Responding to @RobinZigmond's inquiry

filter function is applied to eliminate all non-'Savings' accounts from the array and returns an array of those with type === 'savings'. The resulting array is then passed to the map method.

map operation generates a new array containing only the balances of the savings accounts. Subsequently, this array is handed over to the reduce process.

reduce simplifies multiple elements in an array into a single value. In our context, it takes the array of balances, sums them up, and assigns the result to sum.

const accounts = [
  { acctNo: 123, type: 'Checking', balance: 150 },
  { acctNo: 234, type: 'Checking', balance: 200 },
  { acctNo: 345, type: 'Savings', balance: 550 },
  { acctNo: 456, type: 'Checking', balance: 550 },
  { acctNo: 567, type: 'Savings', balance: 1500 }
];

const sum = accounts
  .filter((account) => account.type.toLowerCase() === 'savings')
  .map((savingsAccounts) => savingsAccounts.balance)
  .reduce((accumulator, balance) => accumulator + balance);

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

Is there a way to individually remove a selected radio button and its corresponding label?

Having trouble removing a selected radio button and its associated label. Struggling to implement the remove function that targets the selected radio button and removes both the button and label. function removeRadioItem() { var radios = document.getElem ...

Ways to retrieve all Exit values from an Array

console.log(data); output: { "Status": "OK", "Message": "", "Data": { "LocationId": 1, "LocationName": null, "LocationData": [ ], "DeviceData": [ ], "AverageData": [ { "Timestamp": "2017-01-01T00:00:00" ...

JavaScript function following AJAX request

I'm attempting to invoke a JavaScript function that is returned in an Ajax call What is the proper way to run a JavaScript function received from an Ajax call? Consider this script before the Ajax call <script> function start(){ console.l ...

ng-view or controller appears to be malfunctioning

I'm currently working on a small web application using AngularJS. I have an index.html file in the main directory and three other HTML pages within the html subdirectory. login.html list.html detail.html Initially, the index.html should load the ...

Using Material-UI version 1, pass the outer index to the MenuItem component when clicked

Within my component, there is a Table that displays rows generated from a custom array of objects. In the last TableCell, I aim to include an icon button that, upon being clicked, opens a Menu containing various MenuItem actions (such as edit and delete). ...

Using nuxt-link with a configuration variable passed as the query parameter key

I am seeking a method to pass an environment configuration variable called process.env.config.myVar to my nuxt-link like this: :to="{ name: 'search-page', query: { process.env.config.myVar: { query: `${searchValue}` } } }" My ...

What is the reason for JSON.parse throwing errors on the same strings that eval does not?

Imagine having something like this: var a = '["\t"]' When you use: eval('var result = ' + a) Everything runs smoothly. However, if you try: var result = JSON.parse(a) You'll encounter an error: Unexpected token. The s ...

What steps should I take to make sure my asp.net validators execute prior to invoking client-side javascript functions?

I am facing an issue with my asp.net application which has basic CRUD functionality. I have set up several asp.net validators on a customer details capture page to ensure required fields are filled out. Additionally, I have added a JS confirm box to the sa ...

Error TS2339: The type 'Element' does not have a property named 'style'

Below is the code snippet to change the style of elements: const test = Array.from(document.getElementsByClassName('mat-form-field-infix')); test.forEach((element) => { element.outerHTML = '<div class="good-day-today" style="width ...

Storing an array within an AngularJS service for better performance

As someone who is relatively new to AngularJS, I am still in the process of understanding how to utilize services for fetching data in my application. My aim here is to find a method to store the output of a $http.get() call that returns a JSON array. In ...

Using AJAX to dynamically update content via HTTP requests

Why do I keep seeing "loading..." instead of the content from data.php? xmlhttp = new XMLHttpRequest(); function fetchData () { xmlhttp.onreadystatechange = function () { if(xmlhttp.readyState = 4 && xmlhttp.status == 20 ...

Displaying a username with HTML and Node.js: A step-by-step guide

Hey there! I'm currently working on a simple login page and I'm looking to display the username once a successful login occurs. However, I'm unsure how to achieve this using just HTML. While I've come across various resources on tools l ...

Embrace the use of square brackets when formatting JSON output

Below is the current output that I am getting: {"name":"a","path":"a","type":"folder","items":{"name":"b","path":"a/b","type":"folder","items":{"name":"c.docx","path":"a/b/c.docx","type":"file","size":"20"}}} I want to modify it to add brackets in the "i ...

What is the best way to remove duplicate objects from an array?

I have come across multiple resources discussing the deletion of duplicate values in objects, such as this, this, this... However, all these examples focus on simple objects whereas my scenario involves more "complex" data. In my case, I have an array whe ...

Simple steps to serialize an object in React and send it to a URL

Is there a way to successfully pass an object via a URL as a parameter and retrieve it in another component? I thought about stringifying the object and passing it as a parameter like this: <li key={something}><Link to={{pathname:`/animal/${JSON. ...

Hidden Password Field Option in HTML

My HTML password textbox has the input type set as password, but I can still see what is being typed. This shouldn't happen as password inputs should be masked. Can someone please advise me on how to resolve this issue? To replicate, copy the code be ...

jinja2.exceptions.TemplateSyntaxError: instead of 'static', a ',' was expected

My current project involves using Flask for Python, and I encountered an error when running the project from PyCharm. The error message points to line 192 in my home.html file: jinja2.exceptions.TemplateSyntaxError: expected token ',', got &ap ...

The GIPHY API object returns no results

Utilizing Angular 2 to fetch data from the GIPHY API. export class ListaGifsComponent { gifs : Object[] = []; urlBase = "http://api.giphy.com/v1/gifs/search?q="; termoPesquisado = "ryan+gosling"; key = "O8RhkTXfiSPmSCHosPAnhO70pdnHUiWn"; ...

Receiving an ambiguous message from the meteor subscriptions

New to using Meteor, I am trying to create a registration form with Meteor. I am facing some challenges with the `findOne` and `subscribe/publish` functions. Here is my `collection.js` file: User_Customer = new Meteor.Collection("USER_CUSTOMER"); Custome ...

Error encountered: Trying to access the property 'top' of an undefined object while selecting a menu item to navigate to a different page

Whenever I try to use my menu on a mobile device, I encounter some issues. The menu functions perfectly on a desktop, but as soon as I switch to a mobile phone, I find myself unable to navigate to different pages. The only functionality that seems to work ...