Using Javascript Reduce to Manipulate Objects

Here is the data I am working with:

let info = [
        {id: 1, name: "John Doe", type: "A", amount: 100},
        {id: 2, name: "Jane Smith", type: "B", amount: 150},
        {id: 3, name: "Alice Johnson", type: "A", amount: 120}
    ]

To get information about the number of accounts and total amount for 'type A' only, I can filter the data like this:

let typeAData = info.filter((item)=>{
        if (item.type === "A") {
            return item;
        }
    })

I can then calculate the number of 'type A' accounts using this:

let numAccounts = typeAData.length;

Furthermore, to calculate the sum of amounts for 'type A', I can use this code:

let totalAmount = typeAData.reduce((acc, item)=>{
        return acc+item.amount;
    },0)

If you have any suggestions for a better or more efficient way to achieve the same result, please feel free to share. Your input would be greatly appreciated.

Answer №1

Utilizing a single .reduce statement, you can add the property to the accumulator only when iterating over objects that have the term shortterm. For a more concise approach, consider using the concise return method.

let data = [
        {acnumber: 1, acname: "Mr X", acterm: "shorterm", acbalance: 150},
        {acnumber: 2, acname: "Mr Y", acterm: "longterm", acbalance: 140},
        {acnumber: 3, acname: "Mr Z", acterm: "shorterm", acbalance: 155}
    ]
const balance = data.reduce(
  (a, obj) => a + (obj.acterm === 'shorterm' ? obj.acbalance : 0),
  0
);
console.log(balance);

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

Having trouble with implementing both filter and infinite scroll simultaneously in an Ionic list?

I've encountered an issue with my ionic hybrid app related to angularjs filters. The code snippet below showcases the problem: <input type="search" placeholder="Search personalities" ng-model="name" ng-change='alert("changed!")&apo ...

Discovering Ajax-powered websites Here are some tips on identifying websites

My goal is to determine if a webpage makes AJAX calls. If the webpage is AJAX-based, I will wait for a few seconds to retrieve the content. If it's not AJAX-based, then I won't wait. I attempted the code below, but it didn't yield any resul ...

Using jQuery to crop an SVG view box

I'm currently working on a sticker website project for a client who requires the ability to crop an image within a specific SVG shape, resembling a Halloween face (shown below). The uploaded image should be displayed only within this shape while hidi ...

Tips for extracting information from a Javascript Prompt Box and transferring it to a PHP variable for storage in an SQL database

My current issue involves a specific function I want my script to perform: before a user rejects an entry on the server side, the system needs to prompt a text box asking for the reason behind the rejection. The inputted reason should then be saved to a My ...

Error message: When initiating AJAX requests in ASP.NET, the function is not defined for undefined

I recently followed a tutorial on creating AJAX requests for CRUD operations in an AngularJS application. However, upon trying to perform an AJAX request to retrieve data from the database, I encountered the following error when launching my application: ...

When a user hovers over an li element, jQuery will dynamically adjust the width of the element based

<ul class="level0"> <li class="level1" id="cat2441"></li> <li class="level1" id="cat2450"></li> <li class="level1" id="cat2455"></li> </ul> <div class="alles-zwei" id="new-cat2441"></div> <div ...

Storing a MySQL query result in a global array in a Node.js environment

Just diving into the world of Node.js and Express, I'm trying to wrap my head around asynchronous functions and global variables. Specifically, I'm working on connecting to a MySQL database, fetching query results, and displaying them on a test.h ...

Issue with the Edit feature causing conflicts with the local storage and generating error messages

There seems to be an issue with my edit function that is causing it to override the local storage when I attempt to save and interfering with my delete function as well. I have searched through similar posts for a solution but have not been able to pinpo ...

Retrieving checkbox value upon form submission

Imagine having a form containing several checkboxes. Upon submitting the form, you aim to display all values of the selected checkboxes. <form> <input type="checkbox" id="product1" name="product1" value="12"> <input type="checkbox" id="prod ...

Vue Js does not include images in the dist directory when the build process is completed

In my VueJs 3 project, I am working with a list of PNG images stored in the src/assets/pngs/ directory. Within my Vue component, I use a For loop to dynamically create the list by setting the image name as the source for the img tag. This implementation wo ...

Issues arise when the Angular controller fails to load

I'm experiencing an issue with my Angular controller where the code inside its constructor is not running. Here's a snippet of the relevant pieces: conversationcontrollers.js: var exampleApp = angular.module('exampleApp',[]); console ...

What is the best way to trigger a controller action when the datepicker's value changes?

Hello, I have a custom datepicker and I am trying to perform a calculation when the year is changed. The code provided below does not seem to work on onchange. I also attempted using the onchange attribute and calling a JavaScript function like this oncha ...

Guide on invoking a function in a PHP file using jQuery's load method

I am having trouble displaying the data retrieved from the database. There is a function called "getComments(page)" in the getComments.php file, where 'page' is an integer parameter corresponding to the chosen database. I need to call this functi ...

Steps to troubleshoot the TypeError: cv.Mat is not a constructor in opencv.js issue

Encountering a problem while trying to use opencv.js for detecting aruco markers from my camera. Each time I attempt to utilize the method let image = new cv.imread('img'); An error keeps popping up: TypeError: cv.Mat is not a constructor ...

Issues with implementing KendoUI's datepicker in conjunction with Angular

My index.html file contains the following imports: <script src="content/js/angular.js"></script> <link href="content/js/kendo.common-material.min.css" rel="stylesheet" /> <link href="content/js/kendo.material.min.css" rel="styleshe ...

The button attached to the jQuery .toggle() function requires two clicks to activate

My objective is twofold: To dynamically load the Disqus script embed.js only when the "Show Comments" button is clicked. To toggle the visibility of the disqus_thread div using the same button while also changing the button's text. The issue I am f ...

Enable vertical scrolling on the second row of a table while keeping the first row fixed as the table header (CSS)

While embedding the Ace Editor in a Chrome popup window, I encountered a challenge. My goal was to keep the first row of text always visible at the top while allowing the rest of the Editor to fill the screen. However, there is an issue with a vertical scr ...

AgGrid supports multi-line content within its cells

I attempted to utilize this solution, however, it is not functioning properly for me. While it does resize the column height correctly, the text is still not wrapped as expected. Ag-Grid - Row with multiline text let gridOptions = { columnDefs: column ...

Javascript - readjust weight distribution accordingly when a weight is removed

I am in possession of a dataset that shows the proportion of each test contributing to the final grade. In cases where a student has missed one or more tests, the weight is redistributed accordingly among the tests they did take. I want to determine how ...

What are the best practices for effectively managing jQuery UI sliders?

I am currently developing a web application that involves updating jQuery UI sliders using JavaScript. While I have managed to resolve most of the issues related to updating the slider after initialization, there is one particular issue that remains unreso ...