Arranging arrays of objects based on their occurrence rate

I am working with an array of objects that looks like this:

students = [
    {
        "name": "Ana Barbique",
        "category":"B"
    }
    {
        "name": "Marko Polo",
        "category":"B"
    }
    {
        "name": "Nick Harper",
        "category":"A"
    }
]

My goal is to create an array of objects in this format:

sum = [
    {
        "category": "A",
        "count" : 1
    }
    {
        "category": "B",
        "count" : 2
    }
]

Basically, I want to extract the categories from the students array along with their count. The order of the categories is not important. This is something I have not attempted before.

Answer №1

Start by generating a categories count object through the reduction of the students array

const categories = students
   .reduce((cat, student) => (
       cat[student.category]++ || (cat[student.category] = 1), cat
   ), {})

Next, loop through the keys of the categories to form the necessary array

const sum = Object
   .keys(categories)
   .map(name => ({category: name, count: categories[name]}))

Answer №2

This code utilizes a pure loop and lookup method to achieve its goal. While Yuri Tarabanko's solution is more elegant, this approach is worth noting.

The crucial aspect of this method involves using the check array object to store the index of each category within the sum[] array. It's a handy technique to be familiar with.

var students = [
    {
        "name": "Ana Barbique",
        "category":"B"
    },
    {
        "name": "Marko Polo",
        "category":"B"
    },
    {
        "name": "Nick Harper",
        "category":"A"
    }
]

var sum = [], check = [], obj;
for (var i = 0; i < students.length; i = i + 1) {

  obj = students[i]; 
  if ( check[obj.category] !== undefined ) { 
    // object has already been seen so add to sum array count
    sum[check[obj.category]].count = sum[check[obj.category]].count + 1; 
    
  }
   else {
   // object has not been seen so insert new.
   sum.push({"category": obj.category, "count": 1});
   check[obj.category] = sum.length - 1; // note index of category in sum array.   
   }


}
console.log('sum = ' + JSON.stringify(sum));

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

Can the html content provided by the user be extracted and highlighted?

When utilizing the onClick function in ReactJS, I am receiving the entire property which includes Lorem Ipsum is simply dummy text. However, I only require the highlighted content like "is simply dummy". Is there a way to achieve this?</p> ...

I want to know how to shift a product div both horizontally and vertically as well as save its position in And Store

How can I animate and move a product div horizontally & vertically, and save its position for future visits? I need to move the div with animation in a specific sequence and store the position using PHP. Buttons <button type="button" href ...

Incorrect behavior of responsive background images

For the first time, I am working on a school project that requires me to create a responsive website. I am following the "mobile first" approach. On stackoverflow, I came across a helpful way of making background images responsive: background-image: url(. ...

Transmitting information from JavaScript to a PHP script

I am currently using a function that grabs text from a PHP file on our server and inserts it into an HTML page. However, I now need to modify this function in order to SEND data (specifically a couple of JavaScript variables) to the PHP file instead of si ...

The jQuery `.load` function appears to be malfunctioning

I am having trouble getting my simple .load() function from jQuery to work. When I click on my DIV, nothing happens. However, the alert TEST does work. <div class="ing">CLICK HERE</div> <div id="overlay3-content"></div> <scrip ...

"Using Vue 3 to teleport content to a specific element and swap out existing

I've successfully implemented the use of Vue 3 teleport to display elements within a div. Although teleport adds items to the specified element, it doesn't replace existing elements in the div. Is there a way to configure teleport to replace th ...

Can a single static variable be shared among all connections on the server?

I am currently working on a turn-based Chinese checkers game. I have added an onload function in the body that sends an ajax request to the server to obtain the player number for the connection. However, I am encountering an issue where the response always ...

Nothing remains after the fall: coding void

I am facing an issue where my item becomes null after being dragged 2-3 times and dropped in a different place. I have included my code below and I can't seem to figure out where the mistake lies. Can you please review it and let me know what needs to ...

Troubleshooting compatibility issues between jQuery scrollLeft and Angular

As I attempt to programmatically scroll a horizontally overflowing div, I am confident that my final code should resemble the following: var $element = $('#widgetRow');//or maybe $('#widgetRow').parent(); //With 1 or more parent()& ...

Using LocalStorage in Greasemonkey

I am currently working on developing a Greasemonkey script, but I am encountering difficulties with implementing local storage within it. The method I found to work with local storage in Greasemonkey involves creating another instance of JavaScript using t ...

What are the best ways to establish communication among JavaScript modules?

I have multiple modules in my application, each with their own responsibilities, but I'm unclear on how they should communicate with one another. What is the best way for modules to interact with each other? How can modules notify or listen to e ...

Do server-side or client-side rendering render dynamic routes in Next.js?

I'm currently working on a project that necessitates server-side rendering for SEO benefits. I am utilizing Next.js and React, implementing Next.js dynamic routing for this purpose. To test if the setup is functioning correctly, I developed a basic p ...

Function defined as an AngularJS component

I am facing an issue where my component is not initializing when I create it with a function that returns a component object. Can someone please help me understand the difference between these two situations? Html: <div ng-app="demoApp"> <navb ...

Extracting the value of *data* from my HTML and displaying it in the console with Javascript

I'm struggling to figure out what's going wrong with this code. I've done some research online and it seems like I should just include the window.onload = function() at the beginning of my code. However, no matter what I try, the value alway ...

Node.JS Logic for Scraping and Extracting Time from Text

Currently, I am working on developing a web scraper to gather information about local events from various sites. One of my challenges is extracting event times as they are inputted in different formats by different sources. I'm seeking advice on how t ...

Comparing getElementById with $('#element') for retrieving the length of an input field

Consider the following scenario: <input type="text" id="apple"> Why does the first code snippet work? $(document).ready(function () { alert($('#apple').val().length); }); However, why does the second code snippet not work as expecte ...

The .value property on the form group displays numeric values as either null or an empty string

I'm encountering an issue with extracting data from a form group. Within my code, there is a formGroup named lineitemForm, and I am attempting to structure this form group as follows: private formatTransferData() { const depositDates = this.get ...

What is the best approach to ensure mobile responsiveness and properly space the TV show div?

How can I center the searched images of shows and add spacing below each image? The 12-column grid is not behaving properly and the images are aligned correctly on desktop but not on mobile. Any suggestions on how to fix this using CSS and Bootstrap? The g ...

Where did my HTML5 Canvas Text disappear to?

I am encountering a common issue with my code and could use some guidance. Despite numerous attempts, I can't seem to figure out why it isn't functioning properly. To better illustrate the problem, here is a link to the troublesome code snippet o ...

Unable to modify the model of the directive

I'm facing an issue where additional elements added to my array within a controller of a directive are not being displayed in the view. What's even more frustrating is that when I print my model, it doesn't reflect the new elements that have ...