Generating a fresh list by extracting elements from an existing array

An array of objects is generated from a mongoDB query representing users' quiz attempts and stored in a variable called res.locals.spellingTestResults. Users can have multiple attempts at the quiz.

[{
        _id: {
            user: {
                name: 'PageHill Class1 Child',
                userType: 'Child',
                email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="22174340151b41411b13111a16124311171b4444161017441362474f52565b0c414d4f">[email protected]</a>',
                __v: 0
            }
        },
        data: [{
                numberOfSpellings: 4,
                wrongAnswers: ['of', 'spellings'],
                rightAnswers: 2,
                score: 2
            },
            {
                numberOfSpellings: 4,
                wrongAnswers: ['spellings'],
                rightAnswers: 3,
                score: 3
            }
        ]
    },
    {
        _id: {
            user: {
                name: 'PageHillAdmin',
                userType: 'Teacher',
                email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4a20232421337979780a2d272b232664292527">[email protected]</a>',
                __v: 0
            }
        },
        data: [{
                numberOfSpellings: 4,
                wrongAnswers: ['first','spellings'],
                rightAnswers: 0,
                score: 3
            },
            {
                numberOfSpellings: 4,
                wrongAnswers: ['of', 'spellings'],
                rightAnswers: 0,
                score: 4
            }
        ]
    }
];

I aim to create an array of objects for each user, combining their wrongAnswers arrays and then counting the instances of each item in the resulting array. The desired output should resemble the structure below:

[{

    user: {
        name: 'PageHill Class1 Child'
    }

    wrongAnswers: {
        'spellings': 2,
        'of': 1
    },

    user: {
        name: 'PageHillAdmin'
    },
    wrongAnswers: {
        'spellings': 2,
        'first': 1,
        'of': 1
    }

}];

While I already have logic in place to combine all the wrong answers across all users, as shown below:

        let allWrongAnswers = [];
        res.locals.spellingTestResults.map(function(answers) {    
            answers.data.forEach(answer => {
                allWrongAnswers = allWrongAnswers.concat(answer.wrongAnswers);
            });
        });

        var countedSpellings = allWrongAnswers.reduce(function (allSpellings, spelling) { 
        if (spelling in allSpellings) {
            allSpellings[spelling]++;
        }
        else {
            allSpellings[spelling] = 1;
        }
        return allSpellings;
        }, {});

My challenge lies in grouping and tallying the wrong answers for each individual user.

Answer №1

Check out this one-shot script:

const dataFromMongo = [
  {
    _id: {
      user: {
        name: 'PageHill Class1 Child',
        userType: 'Child',
        email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0a3f6b683d336969333b39323e3a6b393f336c6c3e383f6c3b4a6f677a7e7324696567">[email protected]</a>',
        __v: 0,
      },
    },
    data: [
      {
        numberOfSpellings: 4,
        wrongAnswers: ['of', 'spellings'],
        rightAnswers: 2,
        score: 2,
      },
      {
        numberOfSpellings: 4,
        wrongAnswers: ['spellings'],
        rightAnswers: 3,
        score: 3,
      },
    ],
  },
  {
    _id: {
      user: {
        name: 'PageHillAdmin',
        userType: 'Teacher',
        email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2b41424540521818196b4c464a424705484446">[email protected]</a>',
        __v: 0,
      },
    },
    data: [
      {
        numberOfSpellings: 4,
        wrongAnswers: ['first', 'spellings'],
        rightAnswers: 0,
        score: 3,
      },
      {
        numberOfSpellings: 4,
        wrongAnswers: ['of', 'spellings'],
        rightAnswers: 0,
        score: 4,
      },
    ],
  },
];

const result = dataFromMongo.reduce(
  (acc, item) => [
    ...acc,
    {
      user: item._id.user.name,
      wrongAnswers: item.data
        .reduce((acc, item) => [...acc, ...item.wrongAnswers], [])
        .reduce((acc, wrongAnswer) => {
          return {
            ...acc,
            [wrongAnswer]: acc[wrongAnswer] ? acc[wrongAnswer] + 1 : 1,
          };
        }, {}),
    },
  ],
  []
);

console.log('result:', result);

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

What's the reason behind the malfunction of this code on Chrome?

After recently installing Mobiscroll, I have been using the date scroller feature with the following code to manage the textbox. <script type="text/javascript"> $(function() { // create a datepicker with default settings $("#begi ...

What is the best way to incorporate CSS conditions within a function?

After creating a filter function in React to organize images by category, I encountered an issue where the filtered images weren't centered as I wanted them to be. I am now looking for a way to integrate centering into the filtering process so that wh ...

React: the props appear to be undefined when they should actually have a value

I have a requirement for my props in the children class to be an array of Event objects. Prior to using it in App.js, I am checking if the array is empty like this: function App() { class Event { constructor(id, title, date){ this.id = id; ...

Exploring the @HostBinding argument in Angular directives

Need help grasping the concept behind the @Hostbinding argument: Snippet of the code: import { Directive, HostBinding } from "@angular/core"; @Directive({ selector: '[appDropdown]' }) export class DropdownDirective { @HostBinding(&apos ...

Is it best practice to store irrelevant context in a separate storage when utilizing the React Context API?

In the process of developing a web app, I have chosen to utilize the React Context API for managing state globally instead of opting for Redux. Currently, I have a store folder alongside my components folder where I store the loggedIn state. As I prepare t ...

How can Entity annotations be accessed with JavaScript in CRM 2011?

Is it possible to fetch Entity annotations using JavaScript in CRM 2011, or is it only achievable through server side code? ...

Is there a way to replicate onbeforeunload in a Vue.js 2 application?

I have a Vue component that is monitoring whether it has unsaved changes. I want to alert the user before they move away from the current form if there are unsaved modifications. In a traditional web application, you could use onbeforeunload. I tried imple ...

Identifying the empty population of a hasMany property

I'm facing a challenge that seems simple, but I'm struggling to find the solution. Currently, I'm working with Emberjs 2.8. In my model, I have an async: true property set up like this: models/my-model.js import DS from 'ember-data& ...

What is the best way to extract the value from a text box that is being looped through using the post method in order to insert it into

I was working with the code below. Each textbox for attendance is looped a certain number of times, and I need to capture the value of each attendance when the form is submitted to insert the values into a database. <form method="post" action="insert. ...

Implementing server authentication for page requests in a nodeJS and angularJS application

My application relies on passport.js for authentication. One of my main requirements is to prevent access to a specific page (e.g., '/restricted') for users who are not logged in. Currently, anyone can directly access the "localhost:3000/#/restr ...

React - utilizing dynamic properties using string values

I am facing a challenge in my test suite where I need to generate components with dynamic props. The desired components should look like this: <Button primary /> <Button secondary /> However, I am currently stuck at this point: [ &apos ...

A perfectly organized and justified menu with evenly spaced horizontal list items

I couldn't find a solution to evenly spacing out a series of list items for a menu styled list. After realizing CSS alone wasn't enough, I decided to incorporate some javascript (jQuery). My goal was to have equal padding between each LI without ...

Enhance Your AG-Grid Experience with a Personalized Colorizing Pipe

I'm having an issue with my AG-Grid implementation in my app. I'm trying to use a custom color pipe that I created in one of the columns using cellRenderer. However, I'm encountering an error and I'm not sure how to fix it. Below is my ...

Concealing loader animation for a sleek user experience with the power of javascript and CSS

If you check out the JSFiddle here <img src="http://www.laneaviation.com/wp-content/themes/laneaviation/images/loading.gif" id="loader" /> var loader = document.getElementById('loader'); I am looking to use JavaScript to hide thi ...

The "DELETE" method in ajax is malfunctioning

I encountered an "internal server error (500)" in the console. When checking my NodeJS console, I received a "ReferenceError: request is not defined" message. Below is the code snippet that caused the issue: $(document).ready(function(){ $('.dele ...

When using jasmine's .toEqual to compare two different objects, one containing an empty object and the other with a key that is a symbol, they are considered equal

Below is an example of my expected statement const otherObject = { [Symbol('what')]: { key: 'value' } }; expect({}).toEqual(otherObject); // This should fail The expectation here is for the test to actually fail. Why does jasmine see ...

Incorporating payment processing into React Native using JavaScript

I am looking to incorporate payment processing into my react native app, but I encountered an issue with using RN's webview as it does not render on the web platform. Additionally, I need to be able to read the response from the server. Can someone re ...

Exploring a property within a JavaScript object

Within my code, I am working with an array of objects called user. When I try to log the first object using console.log(user[0]);, I receive this output: Object {activityId: "2", id: "1", activityDt: "01/15/2016"} Afterwards, I attempt to store user[0] in ...

Tips for managing erroneous data in csv files using Node.js

I am currently working on an application that parses csv files using the csv module. It is functioning well, but I am facing a problem where if there is a bad row in the csv file, the entire process fails. Is there a way to skip bad rows and continue stre ...

Steps to assign the identifier as the current index in the v-for iteration

Struggling to assign the id based on the index of a v-for loop. I attempted: <li v-for="(item, index) in items" v-bind:key="item.id"> <p>{{item.name}}</p> <input id= {{index}} type= "number"> < ...