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

Can the chrome console be used to showcase the contents of objects?

When I have a line of code, and I try to output it to the console, I only see [object Object] instead of the actual object types. console.log(`%c ${args[args.length-1]} ${performance['now'](true, args[args.length-1])} [(${args.slice(0, args.leng ...

How can I align rectangles with different heights to display side by side using Javascript?

Currently, I am designing a press page for a website where the headlines/articles are displayed in rectangles. To achieve this layout, I am using the following CSS: .press-blocks{ column-count: 4; column-gap: 2em; padding-left: 10%; padding ...

Implementing jQuery/JavaScript to efficiently iterate through JSON data

I have implemented a form that allows users to select an item from a multi-select dropdown (A). If the desired item is not listed, users can manually add it using another text input box (B). Once added, an AJAX call saves the item to the database. After su ...

The Node.js express-generator application encounters a problem and is unable to start because of a TypeError: app.set function is not recognized

During the setup of my application using nodejs and express-generator, I encountered an issue when running the following commands in my terminal: npm install multer --save npm audit fix Afterwards, when I attempted to run node ./bin/www I received an err ...

Tips on redirecting the treeview menu using Material-UI 4

Currently, I am utilizing Material UI 4's Treeview component. However, I am struggling to figure out how to include a parameter that allows me to redirect to other pages when the user clicks on an item. In the past, I relied on a different method. Ch ...

Elevate your website's design with Vue and create eye-catching CSS

I've been working on a Vue hamburger menu component, but I'm facing an issue with the animations. The animation process seems to reach the desired end result, yet there is no actual animation displayed. The animation triggering is done through a ...

Check a field for validation only when it is visible on the screen

One challenge I'm facing is with an asp.net webform. I have a hidden field that is only displayed when a user selects a radio button. The catch is, this hidden field needs to be mandatory only when it's visible; otherwise, I don't want it to ...

Every time I refresh the page, the user is automatically logged out

I am currently working on developing an admin dashboard using nextjs 13. I have encountered a specific issue where the user is redirected to the login page every time they reload the page. Upon inspecting in developer mode, I noticed that cookies are still ...

Having trouble loading my app.js in Angular - Seeking help on Coursera!

I've followed the instructions provided thus far and inserted the HTML code accordingly. However, upon attempting to load the page, all I see is: The tabs: The Menu Appetizers Mains Desserts The description: image: dish.name , dish.name , dish.labe ...

Comparing plain objects and class instances for modeling data objects

What is the recommended approach for creating model objects in Angular using TypeScript? Is it advisable to use type annotation with object notation (where objects are plain instances of Object)? For example, let m: MyModel = { name: 'foo' } ...

Can you provide guidance on how to pass the selected value from a select option to an onchange function using Vue.js methods?

I'm facing an issue with passing the selected option value id from a select option to an onchange function in my methods. My goal is to store the selected value in the v-model "choosed" every time the user changes the select option, and then pass that ...

Implement Vue JS to set default value(s) in an array

While browsing through Stack Overflow, I've noticed many questions related to Vue JS and selecting a default single value from an Array. My situation is a bit different - I need to compare each item's array groups with an array containing ALL THE ...

Challenges in generating a PHP array from a CSV file with non-English characters

When working with PHP, I have encountered an issue while trying to create an array from a CSV file using the following code: // CSV file: $csv = array_map('str_getcsv', file("{$uploadPath}/{$myFile}")); Although this code functions correctly for ...

The parent component is failing to pass the form values to the child form group in CVA

My Angular application (view source code on Stackblitz) is running Angular 15, and it utilizes reactive forms along with a ControlValueAccessor pattern to construct a parent form containing child form groups. However, I am encountering an issue where the d ...

What is the significance of the -infinity value in the JavaScript console?

Recently, while learning JavaScript ES6, I came across a strange result of -infinity on my console when running the following code: let numeros = [1, 5, 10, 20, 100, 234]; let max = Math.max.apply(numeros); console.log(max); What does this ...

Navigating through elements in an array in node.js

Within my array, I store the languages that users prefer. Here is an example: let language = [] var Lang = "it" language.push(Lang) This process is repeated with various languages. The array would eventually contain these values: language ...

The updating of Angular 2 CLI variables does not occur

As a complete newcomer to Angular 2, I recently attempted to start my first project using the Angular CLI. Unfortunately, I encountered some issues. It seems that the variables in my views are not updating as expected. I followed the typical steps: ng n ...

Is there a way to display an alert using JavaScript that only appears once per day?

I've created a website that displays an alert to the user upon logging in. Currently, the alert is shown each time the user logs in, but I'm looking to make it display only once per day at initial page loading. How can I achieve this? Below i ...

Discovering the highest value in the final row of a two-dimensional array

I'm currently working on extracting the maximum value from the last column of a specific array and printing it out. Despite attempting to utilize the Double.max() method, I have encountered issues with it not functioning correctly for this particular ...

Switching between filters using AngularJS toggle buttons

Currently, we are in the process of converting a jQuery application into an Angular application using JavaScript. The existing jQuery app functions, but we aim to transform it into a full-fledged app utilizing the Angular framework. The main concept behin ...