JavaScript code that counts the number of objects with matching values

Here is the JSON data I am working with:

 [{
          "semester":"1",
          "classification":"Excellent",
          "schoolYear":"2018"
       },
       {
          "semester":"2",
          "classification":"Intermediate",
          "schoolYear":"2018"
       },
       // More JSON data...
       ]

I need a function to transform this data into the following format:

[
  {
    schoolYear: '2018',
    semesters: [
      {
        Excellent: 2,
        Good: 0,
        Intermediate: 0,
        Average: 0,
        Weak: 0,
        Fail: 0
      },
      {
        Excellent: 0,
        Good: 0,
        Intermediate: 1,
        Average: 0,
        Weak: 0,
        Fail: 0
      }
    ]
  },
  {
    schoolYear: '2017',
    semesters: [ 
    // More formatted data...
    ]
  }
]

In essence, the function should output an array where each element has information for different school years and their corresponding semesters. Thank you in advance for your help! You can access and modify the code in this codesandbox demo here. Have a great day!

Answer №1

Below is a functional example:

var data = [
    {
        section: "A",
        grade: "Excellent",
        year: "2022"
    },
    {
        section: "B",
        grade: "Intermediate",
        year: "2022"
    },
    {
        section: "A",
        grade: "Good",
        year: "2022"
    },
    {
        section: "B",
        grade: "Fail",
        year: "2021"
    },
    {
        section: "C",
        grade: "Excellent",
        year: "2021"
    },
    {
        section: "A",
        grade: "Good",
        year: "2021"
    }
];
const organizeData = (oldData) => {

    const newData = [];
    oldData.forEach((oldEntry) => {
        let newIndex = newData.findIndex((e) => e.year === oldEntry.year);
        if (newIndex === -1) {
            newData.push({
                year: oldEntry.year
            });
            newIndex = newData.length - 1;
        }
        if (!newData[newIndex].section) {
            newData[newIndex].section = [];
        }
        if (!newData[newIndex].section[oldEntry.section]) {
            newData[newIndex].section[oldEntry.section] = {};
        }
        newData[newIndex].section[oldEntry.section][oldEntry.grade] = newData[newIndex].section[oldEntry.section][oldEntry.grade]
            ? newData[newIndex].section[oldEntry.section][oldEntry.grade] + 1
            : 1;
    });
    return newData;
};
console.log(organizeData(data));

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

Switches in a React-Native ListView are not refreshing properly

Situation: I encountered an issue with a ListView of Switches Problem: The Switches are not changing state when pressed. When debugging, each switch appears to be checked momentarily after the setValue function is called, but then reverts back to unchecked ...

Issue with bidirectional data binding in Angular 2 on input element not functioning as expected

Looking at the code snippet below, I have noticed that even though the textchange function is called when the input value changes, the text property of the InputMaskComponent remains constant. I am not able to identify the issue in my code. InputMaskCompo ...

Component fails to re-render after token refresh on subsequent requests

Here is my axios-hoook.js file, utilizing the axios-hooks package. import useAxios from 'axios-hooks'; import axios from 'axios'; import LocalStorageService from './services/local-storage.service'; import refreshToken from &ap ...

A guide on transferring documents between collections using Mongoose and MongoDB

I have a list of tasks that includes both completed and incomplete items. Additionally, I have two buttons - one for deleting an item (which is functional) and the other for marking an item as done or not. I am struggling with creating a function to move ...

Utilizing Vue.js to apply conditional statements or filters on v-for generated outputs

Currently, I am working on organizing my results by category. I believe there is room for improvement in the way it's being done: <div><h2>Gloves</h2></div> <div v-for="stash in stashes" :key="stash.id"> <div v-for= ...

Employing the Scanf function to capture user inputs of varying lengths

Is there a way to make the scanf function work with both single and double number inputs from the user and store them in an array? I'm having trouble figuring out how to use the same function for both scenarios. For example, if the user enters "9 0", ...

retrieve data from a multidimensional array

I am working with an array: array(5) { [0]=> array(2) { [0]=> string(5) "REFER" [1]=> string(12) "Não Sócios" } [1]=> array(2) { [0]=> string(5) "REFER" [1]=> string(12) "Não Sócios" } [2]=> array(2) { [0]=> str ...

When building with Angular using the "ng build" command, the JavaScript file names are altered

I'm currently learning Angular and I've noticed that when creating a new project with Angular CLI, files like runtime.js, polyfills.js, main.js, styles.css are generated. However, after running the ng build command, similar files can be found in ...

The second Ajax request has been filled with successful results

Every time I press a button, an Ajax call is made which fetches data and creates a grid. The first time this function is executed, everything works perfectly - the Ajax call is successful, data is retrieved, and the grid is displayed. However, subsequent c ...

Leveraging associative arrays in PHP to extract information commencing from a specific datum

Although it may seem simple, I encountered a minor catastrophe while trying to solve this particular issue. My PHP associative array resembles the following: $people= array (["Name" => "Sandra", "Age" => "21"], ["Name" => "Frank", "Age" => "34 ...

JS on-click function is not functioning

Here is the HTML code I have for my navigation menu: <nav role="navigation" class="nav"> <ul class="nav-items"> <li class="nav-item"> <a href="#" class="nav-link"><span>About Us</span></a> ...

Arrange an asynchronous function in Node.js

I have been attempting to set up a schedule for an asynchronous function (with async/await return type) to run every two minutes. Although I have tried using the generic setInterval, as well as various node modules such as node-schedule, cron, node-cron, ...

How to Retrieve JSON Data in PHP

Check out this JSON data I found at http://pastebin.com/5VeJ5dda I'm trying to figure out how to access the ipaDownloadUrl on each case and store them in two variables using PHP. I've already started with the following code: <?php $api = url ...

jQuery for Implementing Pagination Across Multiple Tables

As a novice in the world of JavaScript and jQuery, I am struggling with implementing pagination for multiple tables on a single page. My goal is to have several tables that can be paginated using one navigation system. However, all my attempts so far have ...

Show the div only if a different ID is activated

I seem to be having trouble targeting only one div element. Specifically, when I click on "impressum," only the impressum content is displayed within the <div class="ContentBox">. However, when I click on "AboutMe," both the AboutMe and impressum co ...

Distinguishing Hex Colors in Threejs

While working on my material, I decided to use the hex code 0x205081 like this: material = new THREE.MeshBasicMaterial({color: 0x205081, vertexColors: THREE.FaceColors}); However, when I attempt to revert a few colors back to the original shade (0x205081 ...

Interacting with API through AngularJS $http.get

I am a beginner in AngularJS and I am trying to grasp its concepts by studying example codes. Currently, I have found an interesting code snippet that involves the $http.get function. You can find it here: I attempted to replace the URL with my own, but ...

The ng-bind directive is functional when used with a textarea element, but it does not work with

Recently diving into the world of angularjs, I stumbled upon ng-bind and its interesting functionality when used as a directive for textarea: <input type="text" ng-model="review.start"/> <textarea ng-bind="review.start"> </textarea> I ...

Learn how to efficiently showcase information extracted from a complex JSON object in VueJS 3 using Vuex

Hello friends, I've been grappling with this issue for quite some time now, despite following basic tutorials. In my Vue 3 project, I'm trying to display JSON data. When the data is within an array and I use a loop, everything works fine. Howev ...

Is there a way to collapse child elements in a hover sidebar using Vuetify?

My project includes a sidebar that opens when I hover over it with the mouse. Everything works fine, but within the sidebar, there is a collapse dropdown menu. When I open this menu and then move the mouse away from the sidebar and back again, the collapse ...