Combining a group of JavaScript objects

I am facing a challenge with my collection as I need to perform aggregation using only JavaScript. I have attempted various approaches utilizing the Lodash library but unfortunately, I have not been successful. If you could provide me with some guidance on how to group a collection, I believe that would solve my issue.

var sample = [
        {
           

            "DESCRIPTOR": "HAPPY",
            "DESCRIPTOR_ID": 400001,
            "QUESTION_ID": "A_QUES_1",
            "CHOICE": "A",
            "SCORE": 1,
            "__v": 0
        },
        {
           

            "DESCRIPTOR": "HAPPY",
            "DESCRIPTOR_ID": 400001,
            "QUESTION_ID": "A_QUES_2",
            "CHOICE": "B",
            "SCORE": 2,
            "__v": 0
        },
{
           

            "DESCRIPTOR": "SAD",
            "DESCRIPTOR_ID": 400002,
            "QUESTION_ID": "B_QUES_1",
            "CHOICE": "A",
            "SCORE": 2,
            "__v": 0
        },
        {
           

            "DESCRIPTOR": "SAD",
            "DESCRIPTOR_ID": 400002,
            "QUESTION_ID": "B_QUES_2",
            "CHOICE": "B",
            "SCORE": 2,
            "__v": 0
        }
    ]

I am looking for an outcome similar to the following:

 result = [{"DESCRIPTOR": "HAPPY", "TOTAL_SCORE":3}, {"DESCRIPTOR": "SAD", "TOTAL_SCORE":4}]

I require assistance in writing this scripting code solely in JavaScript. Thank you.

Answer №1

To achieve this task, utilize the array reduce method like so:

let finalResult = data.reduce((previous, current) => {
   const name = current.NAME;
   const index = previous.findIndex((item) => item.NAME === name);
   if(index > -1){
      previous[index].VALUE += current.VALUE;
   } else {
      previous.push({'NAME': name, 'VALUE': current.VALUE});
   }
   return previous;
}, []);

console.log(finalResult);

Answer №2

The following code organizes the objects based on DESCRIPTOR_ID. To achieve this, iterate through the arrays using the Array.prototype.reduce() method to extract the descriptor_id and set it as a key, then calculate the total score for each key. Finally, retrieve the values using the Object.values() method.

const sample = [
  {
    DESCRIPTOR: 'HAPPY',
    DESCRIPTOR_ID: 400001,
    QUESTION_ID: 'A_QUES_1',
    CHOICE: 'A',
    SCORE: 1,
    __v: 0,
  },
  {
    DESCRIPTOR: 'HAPPY',
    DESCRIPTOR_ID: 400001,
    QUESTION_ID: 'A_QUES_2',
    CHOICE: 'B',
    SCORE: 2,
    __v: 0,
  },
  {
    DESCRIPTOR: 'SAD',
    DESCRIPTOR_ID: 400002,
    QUESTION_ID: 'B_QUES_1',
    CHOICE: 'A',
    SCORE: 2,
    __v: 0,
  },
  {
    DESCRIPTOR: 'SAD',
    DESCRIPTOR_ID: 400002,
    QUESTION_ID: 'B_QUES_2',
    CHOICE: 'B',
    SCORE: 2,
    __v: 0,
  },
];

const ret = Object.values(
  sample.reduce((prev, c) => {
    const p = prev;
    const key = c.DESCRIPTOR_ID;
    if (!p[key]) p[key] = { DESCRIPTOR: c.DESCRIPTOR, TOTAL_SCORE: c.SCORE };
    else p[key].TOTAL_SCORE += c.SCORE;
    return p;
  }, {})
);
console.log(ret);

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

Utilizing Async.each fails to trigger the ultimate callback function

Here's the scenario: I expect the function finalCallBack to be triggered after we finish looping through all elements. var rows = [ { name: 'first'}, { name: 'second'} ]; var execForEachRow = function(row, callback){ var ...

Injecting a component in Angular 2 using an HTML selector

When I tried to access a component created using a selector within some HTML, I misunderstood the hierarchical provider creation process. I thought providers would look for an existing instance and provide that when injected into another component. In my ...

The setState function in React Native seems to be having trouble updating

I've been attempting to access state from a component, but for some reason, I'm not seeing any changes when I use setState(). Here is the current state of my component: class MyTestComponent extends React.Component { constructor(props){ ...

Obtaining a UTC datetime value in BSON format using Node.js or JavaScript

I'm encountering an issue while attempting to save an entry in a MongoDB time series collection. The problem arises when storing the timeField, resulting in an error thrown by mongo. MongoServerError: 'blockTime' must be present and contain ...

What is the best way to retrieve the offsetHeight of a Component Element using Vue.js?

I am currently working on a Vue.js component and successfully inserting it into the DOM. My goal is to find out its rendered height once it's in the DOM, specifically its offsetHeight. However, I seem to be missing something obvious as I can't fi ...

Guide on retrieving an ArrayList() from intricate function in Angular

Simplicity is the key to my question. Let's take a look at this Angular method: getAllOrdersHeaders(){ this.getAllOrdersIds().subscribe(idList=>{ idList.forEach(id=>{ this.ordersCollection.doc(id).collection('metadata&apo ...

When validated, the Yup.date() function seamlessly converts a date into a string without including the timezone

Currently, I am integrating Yup with react-hook-form and have defined the following schema in Yup: const validationSchema = Yup.object({ installation: Yup.string().nullable().required("Required"), from_date: Yup.date() .max(new Date(), "Can ...

Is it possible to incorporate numerous instances of SlickGrid by utilizing an angular directive?

Just started diving into AngularJS and it's been an exciting journey so far. I've come across the suggestion of wrapping external libraries into directories, which definitely seems like a good practice. While trying to create a 'slickgrid& ...

What are the steps for showcasing a personalized HTML tag on a web page

I need to capture user input text and display it correctly. This is what I have attempted: <div> <input type="text" ng-model="post.content" /> </div> <div> <div ng-bind-html="post.content| htmlize"></div> < ...

Tips for ensuring a custom menu closes when clicking outside of it instead of on the menu itself

Building off a recent inquiry, I am aiming to have my menu close whenever I click outside of it. At the moment, clicking the "Hamburger Menu Button" opens and closes the menu. It will also close when I click a link on the menu or the menu itself. However, ...

Revamp your JavaScript code to trigger when the clock strikes bold!

Having trouble setting up JavaScript to automatically bold the next clock time. Any tips on rewriting the JavaScript? For instance, if it is currently 6:49, I want the next clock time of 7:32 to be automatically bolded. And when the time reaches 7:32, I wa ...

Tips for translating an HTML webpage from Arabic to English

I have a bootstrap site with HTML pages but no backend functionality. How can I manually translate from Arabic to English, given that I already have the translations for all content and don't need to rely on translation tools? Is there a way to map Ar ...

Transforming a single word into three identical arrays

Currently I am tackling a project where my goal is to divide a word into 3 arrays of equal length. Here is the code snippet that I have been working on, but unfortunately it doesn't seem to be functioning properly. String password = JOptionPane.showi ...

Vue appears to be having trouble waiting for the axios Post request

While testing a login request, I encountered an issue where jest did not call the mock: This is my test : const User = '123123' jest.mock('axios', () => ({ get: jest.fn(), post: (_url, _body) => new Promise((resolve, reject ...

My element is not being animated by Elementbyclass

Without Using JQUERY The animation I'm trying to create isn't functioning properly. I attempted to utilize document.getElementsByClassName, but it's not working as expected. There are no errors, but the element is not animating correctly. ...

Tips for displaying a message in the model body when a bootstrap model does not have any data in jQuery

Having trouble displaying a text message in the Bootstrap modal body when there is no data available in the model. I have multiple cards in the model, and if I click on the skip or done buttons, each card will close. However, if there is only one card in t ...

What is the most efficient method for designing this jQuery code to be reusable?

I am currently using dynamic Bootstrap popovers that are populated with content from my database. In PHP, it generates unique classes for each popover. My question is, when using jQuery, do I need to trigger the popovers individually? This is how I am cur ...

Troubleshooting issue with changing class based on input values

It appears that there is an issue with the functionality when switching values on page load. Initially, I was able to make it work for a single switch, but now that there are multiple switches on the page, toggling affects all of them. How can I modify it ...

What is the best method for transferring form data to a string and storing it in localStorage effectively?

Is this the most efficient method for extracting form data into a string and storing it in localStorage? I developed this method independently, but I'm not an experienced programmer. It seems to work for my needs, but I'm unsure if it's com ...

Having trouble getting Highcharts SVG element to refresh? Looking to incorporate custom freeform drawing features within Highcharts?

I have implemented highchart for graph rendering and utilized the renderer to draw a custom line within the chart. I am looking for a way to recalculate and repaint this path whenever there is a change in data. The framework being used is highcharts-ng alo ...