Tips for inserting items into an array of objects?

I have an array of objects with categories and corresponding points, and I need to calculate the total points for each category.

   {
     category: A,
     points:2
    },
    {
      category: A
      points: 3
    },
    {
     category: B,
     points:2
    },
    {
      category: B
      points: 3
    }
   ]

What is the most efficient way to sum up the points for category A and category B separately?

Answer №1

Here is a piece of code that might be useful for you

arr = [{
         category: 'A',
         points:2
        },
        {
          category: 'A',
          points: 3
        },
        {
         category: 'B',
         points:2
        },
        {
          category: 'B',
          points: 5
        }]
    
    let total = 0;
     arr.filter(function(item){
            return total += item['points']
        });

console.log(total)

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

Transform a string into an object using AngularJS $parse function

Imagine having a server that sends back a response in the form of: { multiply:function(x,y) { return x*y; }, divide:function(x,y) { return x/y; } } Can this be converted into a functional method? I attempted to convert ...

Guide to resetting all ReactiveVars to false in Meteor JS

I am currently working on a recipe template where I am using {{#each recipes}} to render the recipes. I have implemented ReactiveVar to toggle the edit form of each recipe from hide to show. Everything is functioning correctly, but I want to ensure that ...

Attempting to create a single function that can be utilized with numerous divs that share the same class in jQuery

Currently, I am working on creating a basic jquery gallery viewer. In my code, I have the following structure: <div class="photoset"> <img /> <img /> </div> <div class="photoset"> <img /> <img /> <i ...

Creating a React Native project without the use of TypeScript

Recently I dived into the world of React Native and decided to start a project using React Native CLI. However, I was surprised to find out that it uses TypeScript by default. Is there a way for me to create a project using React Native CLI without TypeS ...

Adapt the dimensions of the iframe to perfectly match the content within

Looking for a way to dynamically adjust the size of an iframe to perfectly fit its content, even after the initial load. It seems like I'll need some kind of event handling to automatically adjust the dimensions based on changes in the content within ...

Transform an array into an array of objects using the reduce method

optimizedRoute = ['Bengaluru', 'Salem', 'Erode', 'Tiruppur', 'Coimbatore'] result = [ {start: bengaluru, end: salem}, {start: salem, end: erode}, {start: erode, end: tiruppur}, {start: tiruppur, en ...

Update the array state based on the selection of checkboxes and user input in real-time

In my current project using react js, I am working on a UI development task where I need to create a dynamic table based on data fetched from an API. Each row in the table includes a checkbox and a text input field that are dynamically generated. My goal i ...

Creating an HTML form to collect user data and then automatically saving it to an Excel file stored in a shared Dropbox account

I am looking to extract data from a user form on a website and then automatically save it as an Excel file in a designated Dropbox account once the user clicks submit. Instead of receiving multiple emails every time the form is filled out, I would like t ...

What are the steps for incorporating subelements into a fresh array?

My array consists of nested arrays, each containing only one value. I managed to flatten the array, but I can't shake the feeling that there might be a better way to do it. Is this approach optimal, or is there room for improvement? <?php $array ...

Transfer the array using Ajax to a PHP script

I have an array generated using the .push function that contains a large amount of data. What is the most effective way to send this data to a PHP script? dataString = ??? ; // Is it an array? $.ajax({ type: "POST", url: "script.php" ...

The boxslider plugin is malfunctioning when accessed in Sitecore's preview mode

Even though the Boxslider plugin works when we view the page in a browser, it fails to function properly when the same page is viewed in Sitecore's Preview mode. This issue can be replicated by navigating to Presentation in the top menu, then selectin ...

Preventing Users from Accessing NodeJS Express Routes: A Guide

Currently, I am working on a React application where I am utilizing Express to handle database queries and other functions. When trying to retrieve data for a specific user through the express routes like so: app.get("/u/:id", function(req, res) { ...

The day text function failed to return a value and instead gave back

I am having trouble figuring out where the mistake is in my function below. My goal is to retrieve the day value in string format. function getDayText(date){ var weekday = new Array(7); weekday[0]= "Sunday"; weekday[1] = "Monda ...

Issue with setting innerHTML of element in AngularJS app upon ng-click event

Look at this block of HTML: <div class="custom-select"> <div class="custom-select-placeholder"> <span id="placeholder-pages">Display all items</span> </div> <ul class="custom-select- ...

Utilize load-grunt-configs and run bower.install() with grunt

I have been attempting to break down my current Gruntfile into smaller parts for better clarity. However, I have encountered a hurdle while using bower.install to manage project dependencies. My directory structure appears as follows: package.json bower.j ...

What is the process for importing a JSON5 file in Typescript, just like you would with a regular JSON file?

I am looking to import a JSON5 file into a JavaScript object similar to how one can import a JSON file using [import config from '../config.json']. When hovering over, this message is displayed but it's clearly visible. Cannot find module & ...

Is there a way to access the data attribute value from one component in another component without relying on an event bus mechanism?

In the 'App.vue' component, there is a data attribute called 'auth' that indicates whether the user is logged in. If it is empty, the user is not logged in; if it contains 'loggedin', then the user is authenticated. Now, let& ...

Jquery form submission is failing, and a JavaScript warning appears in the console stating that 'body.scrollLeft is deprecated in strict mode' instead

In my JavaScript file, I've written the following code: function PS_SL_HandleEvent() { $(document).ready(function() { $('#form').removeAttr('onsubmit').submit(function(e) { if(acceptCGV()) { ...

Sending information to a Flask application using AJAX

Currently, I am working on transferring URLs from an extension to a Flask app. The extension is able to access the current URL of the website. I have set up an AJAX request to connect to Flask, and the connection is successful. However, when trying to send ...

What is the best way to download the entire page source, rather than just a portion of it

I am currently facing an issue while scraping dynamic data from a website. The PageSource I obtain using the get() method seems to be incomplete, unlike when viewing directly from Chrome or Firefox browsers. I am seeking a solution that will allow me to fu ...