Calculate the total of all the numerical data within a collection of objects stored in an array

I have an array of objects structured like this:

 data: [
        a:[
            {keyone:'a', keytwo: 'anna', keythree: 23, keyfour: 15},
            {keyone:'a', keytwo: 'anna', keythree: 23, keyfour: 15},
            {keyone:'a', keytwo: 'anna', keythree: 23, keyfour: 15},
            {keyone:'a', keytwo: 'anna', keythree: 23, keyfour: 15}
        ]
    ]

The task is to identify all keys with numeric values, sum them up, and create a new object with the key and its corresponding sum.

The expected result should be:

sums = { keythree: 92, keyfour: 60 }

I am currently using Lodash library for this. Here is my existing code:

//Get all group names
    var keys = Object.keys(data);

    //Iterate through each group
    for(var i = 0; i< keys.length; i++) {
        //For each user record in the group
        _u.forEach(data[keys[i]], function(item) {
            //Identify keys with numeric values
            var numKeys = Object.keys(_u.pick(item, _u.isNumber));

            //Calculate sum for each numeric key
            _u(numKeys).forEach(function(n) {
                _u.set(sums, n+'['+keys[i]+']', _u.sum(_u.map(data[keys[i]], n)));
            }).value();
        });
    }

The current implementation works as intended, but I am looking to optimize it by reducing loops for better efficiency. I believe Lodash might offer a more efficient solution, although navigating the documentation can be challenging.

Answer №1

Give this code a try

var data = {
  a: [
    { keyone:'a', keytwo: 'anna', keythree: 23, keyfour: 15 },
    { keyone:'a', keytwo: 'anna', keythree: 23, keyfour: 15 },
    { keyone:'a', keytwo: 'anna', keythree: 23, keyfour: 15 },
    { keyone:'a', keytwo: 'anna', keythree: 23, keyfour: 15 }
  ],
  
  b: [
    { keyone:'b', keytwo: 'any', keythree: 10, keyfour: 100 },
    { keyone:'b', keytwo: 'any', keythree: 10, keyfour: 100 },
    { keyone:'b', keytwo: 'any', keythree: 10, keyfour: 100 },
    { keyone:'b', keytwo: 'any', keythree: 10, keyfour: 100 }
  ]
};

var result = _.mapValues(data, function (e) {
  return _.reduce(e, function (prev, current) {
    return _(current)
      .pick(_.isNumber)
      .mapValues(function (value, key) {
         return (prev[key] || 0) + value;
      })
      .value();
  }, {});
});

console.log( result );
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>

Answer №2

Below is a method that utilizes the reduce() function:

_.reduce(data, function(result, item) {
    return _.merge(result, _.pick(item, _.isFinite), _.add);
}, {});

During each iteration, the merge() function updates the reduce accumulator. By using pick() and isFinite(), only numerical values are merged. The add() function combines two values for a specific key value. This acts as a customizer function for the merge().

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 parseJSON function is not compatible with AJAX requests

I am attempting to use ajax and retrieve JSON data in WordPress. Here is my Ajax code: $.ajax({ type: "POST", dataType : 'html', url: "/wp-content/themes/myproject/ajax/otros_alojamientos.php", da ...

How to retrieve an array from an object using React

In the context of my React application, I have a function called Query2 within a file named service.ts. The structure of this function is as follows: interface Result { products: number[]; } export async function Query2(molsSdf: string): Promise<Res ...

Exploring the distinctions in e2e testing for select (dropdown), input radio, and input checkbox elements within AngularJS

In AngularJS, testing form attributes can be a bit inconsistent. While the updated e2e testing with Protractor helps, those still using older versions may struggle. I am interested in understanding the differences between: Ways to select items: 1a. Selec ...

Struggling to figure out how to properly shuffle my deck of cards array in JavaScript. Can't seem to grasp how to pass the array correctly

Currently, I am engrossed in my personal project and watching tutorials just for the fun of it. My goal is to create a game for my school project which is inspired by a war card game that I used to play as a child - where the highest number wins. I have ...

Dynamic column group in Datatable - toggle visibility based on user selection

In my application, I am utilizing Jquery datatable with a table that includes the following columns: Name, Office, A1, B1, Diff1, A2, B2, Diff2, A3, B3, Diff3, A4, B4, Diff4 Additionally, there is a select box containing the options: 1. All 2. Diff1 3. D ...

The VueJS component failed to import successfully

Trying a simple demo to explore VueJS components, but encountering an error when loading the page: Unexpected Token Import in this line import GISView from './components/GISView.vue'; If I remove this line, GISView is not defined. Using Laravel ...

Utilizing HTML to emphasize a section of text

Hey there! I have a question related to an image with unicodes. The letter featured in the image was written using unicode characters పా. I'm trying to highlight the white portion of the image, but simply replacing it with ా isn&apos ...

Utilizing Vue: Attaching click event to dynamically added elements

I am working on a Vue application that retrieves HTML content from an API. This HTML contains blocks with the class <div class="play-video">...</div> Using axios to call the API and a promise, I insert the content into the DOM like this: < ...

Using JavaScript variables to implement real-time functionality through AJAX

I'm using PHP to fetch values from a database and need to display them in real-time as they change every second. Here is my PHP code: $sql = 'select * from cpu_usage where id=(select max(id) from cpu_usage)'; $login ='select count(*) ...

Managing data overload in Node.js can lead to Promise Rejection Warnings

I'm currently developing a feature where scanning a barcode adds the product information to a table. Once the data is in the table, there is a button to save it. Each row requires generating a unique stamp and inserting into tables named bo, bo2, and ...

Mastering the art of looping and implementing logic in JavaScript using Regular

Unsure if it is possible to achieve this using regex under JavaScript, but I found the concept interesting and decided to give it a try. I wanted to clean up some HTML code by removing most tags completely, simply dropping them like <H1><img>& ...

An error occurs stating 'TypeError: d is undefined' while transitioning on a bar chart triggered by a mouseover event

While working on incorporating transitions into my bar chart, I encountered an issue where they would start from the axis and rise up to the desired height. Although I managed to get the transitions to function properly, the mouseover event stopped working ...

Is there a way to verify that all of my HTML elements have been loaded in AngularJS?

I am currently utilizing angularJS version 1.2.1 along with angular-ui-bootstrap. Within my code, I have a collection of <ng-includes> tags from angularjs and <accordion> components from angular-ui. When loading the content, I need to initiat ...

What is the best way to centrally align a Card while keeping the text left-aligned?

New to coding and need some guidance. I'm attempting to create a card that is not the full width of the window. I have specified a cardStyle as shown below. cardStyle:{ width: '95vw' align? : 'center?' textAlign? : &a ...

Is there a way to collapse just one specific row in Angular?

I am struggling to toggle only the selected row, any suggestions? Take a look at my code and demonstration here: https://stackblitz.com/edit/test-trainin-2-gv9glh?file=src%2Fapp%2Fapp.component.scss Currently, all rows are being toggled when clicked, but ...

What is the best method for converting input files into FormData?

I recently created a form that allows users to upload both an audio file and an image file simultaneously. However, during testing, I noticed that the alert only displays basic data and does not include the form data. function PodcastUpload({ data }) { ...

What is the best way to establish a fixed height for an accordion?

Is there a way to adjust the height of jQuery UI Accordion to a specific value? Am I overlooking any essential steps? ...

PhoneGap 3.5.0 FileTransfer onprogress issue unresolved

I can't seem to get the onprogress event handler to work when downloading a file. The success callback is triggered and the download goes through successfully, but for some reason, the progress events are not firing. Does anyone see any issues with my ...

Maintaining the 'loggedIn' state across refresh in React

Hello, I am new to React and single page applications in general. I am currently working on making my login state persistent across my application, but I am facing issues when the user refreshes the page. Currently, I have a method in my login form that co ...

Order modules in a specific sequence in Node.js

I am facing an issue where the invoke action is being called before the validate file function in my code. I have been trying to figure out how to ensure that validateFile is called before appHandler.invokeAction. Would using a promise be a suitable soluti ...