Determine the number of occurrences of specific values within a group of objects based on a

I have the following dataset:

const data2 = [
{
  App: "testa.com",
  Name: "TEST A",
  Category: "HR", 
  Employees: 7
},
{
  App: "testd.com",
  Name: "TEST D",
  Category: "DevOps", 
  Employees: 7
},
{
  App: "teste.com",
  Name: "TEST E",
  Category: "DevOps", 
  Employees: 7
},
{
  App: "testf.com",
  Name: "TEST F",
  Category: "Business", 
  Employees: 7
}
]

I am trying to extract the count of unique categories from this data. Currently, I can list all distinct categories but I am struggling to calculate their respective counts.

The code snippet below helps me in getting the Unique Categories:

  let uniqueCategory = [];
  for(let i = 0; i < result.data.length; i++){    
      if(uniqueCategory.indexOf(result.data[i].Category) === -1){
        uniqueCategory.push(result.data[i].Category);        
      }        
  }

What modifications do I need to make in order to obtain the Counts of each Category in the uniqueCategory array? The desired output should resemble something like this:

uniqueCategory = [
  {Category: "DevOps", count: 5},
  {Category: "Business", count: 4},
  ....
  {}
]

Answer №1

Your current method involves iterating over your source array (using `.indexOf()`) in each iteration of the `for(..` loop. This can slow down the lookup process unnecessarily.

Instead, consider utilizing the Array.prototype.reduce() function to iterate over your source array and construct a Map. This Map will have `Category` as the key and an object in the desired format as the value. You can then extract the values using Map.prototype.values() into the resulting array.

This approach will enhance performance significantly and offer better scalability.

const src = [{App:"testa.com",Name:"TEST A",Category:"HR",Employees:7},{App:"testd.com",Name:"TEST D",Category:"DevOps",Employees:7},{App:"teste.com",Name:"TEST E",Category:"DevOps",Employees:7},{App:"testf.com",Name:"TEST F",Category:"Business",Employees:7}],

      result = [...src
        .reduce((r, {Category}) => {
          const cat = r.get(Category)
          cat ? cat.count ++ : r.set(Category, {Category, count: 1})
          return r
        }, new Map)
        .values()
      ]
    
console.log(result)
.as-console-wrapper{min-height:100%;}

Answer №2

The most efficient method is utilizing the Array.prototype.reduce function

const arr = [ ... ];
const result = arr.reduce((accumulator, item) => {
  if (!accumulator[item.type]) {
    accumulator[item.type] = 0;
  }

  accumulator[item.type]++;

  return accumulator;
}, {});
console.log(result); // this will display the desired output

Answer №3

Here is an alternative approach utilizing .map along with Set:

const data = [
{
  Site: "example1.com",
  Name: "Example 1",
  Category: "Tech", 
  Employees: 10
},
{
  Site: "example2.com",
  Name: "Test 2",
  Category: "Marketing", 
  Employees: 20
},
{
  Site: "example3.com",
  Name: "Example 3",
  Category: "Tech", 
  Employees: 15
},
{
  Site: "example4.com",
  Name: "Test 4",
  Category: "HR", 
  Employees: 30
}
];

const categoriesList = data.map(item => item.Category);
const uniqueCategories = [...new Set(categoriesList)];
console.log(uniqueCategories.length);

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

Position the colored div on the left side of the page

Here is the CSS I am currently using... <style type="text/css"> .widediv{width:1366px;margin-left:auto;margin-right:auto} </style> This CSS code helps me create my webpage : <body><div class="widedivv"> <!-- Content go ...

Having trouble with passing the callback for nested mysql queries in Async.waterfall?

I am facing an issue with my nested MySQL queries where async.waterfall is not working as expected. The second step of the waterfall is failing to append its result to the array: async.waterfall([ function(callback) { connection.query(query, function( ...

Populate a shopping cart with items using AngularJS

Greetings from an Angular newbie! I'm currently working on developing a shopping cart specifically designed for college students. The objective is to input the name and price of items into a text field and upon clicking a button, have the item added t ...

Utilize a Sails.js Single Page Application (SPA) to route all unutilized paths to a centralized controller function

I'm currently working on a project where I am building a single page application (SPA) with Sails.js as the backend. My goal is to have all routes redirect to a single controller action. However, the issue I am facing is that when I try the following ...

Create a repeating function that will show an image based on the specific class assigned to each individual element

Can someone help me create a function that automatically applies to all divs with a specific class on my document? I want the function to check for the presence of another class within those divs and display an image accordingly. document.getElementsByCla ...

Vuetify 3 now displays full text in v-autocomplete without an ellipsis

Trying to truncate long text in a v-autocomplete component using Vuetify 3 and text-overflow: ellipsis, but it's not working. Check out the code below: <div id="app"> <v-app id="inspire"> <v-row align="cen ...

Encountered a cyclic dependency in MongoDB when attempting to create an index

I have a dataset structured as shown in the image below: https://i.sstatic.net/eu2ZH.png I am attempting to write a query using $near. However, when trying to create an index for this query, I encounter an error stating "cyclic dependency detected". Below ...

The onsubmit function is not functioning correctly in combination with Ajax

My current implementation involves utilizing Ajax and Php for user login validation. Unfortunately, the form onsubmit function is not properly functioning. <form action="loggedin.php" onsubmit="return test()" method="post"> Below is the correspondi ...

JS Emphasis on Scrolling Div

I'm facing an issue with a button that opens a scrollable div. When I try to use the arrow keys on the keyboard, they do not scroll the div as expected. Interestingly, if I click anywhere on the div, then I am able to scroll using the arrow keys. I ...

Material UI - Exploring the Tree View Component

Seeking advice on structuring server data for utilization with the TreeView component from Material UI: https://material-ui.com/api/tree-view/ I need to efficiently handle large datasets by fetching child nodes dynamically from the server upon user intera ...

The script is stuck displaying the existing records, failing to update with any new ones

Kindly refrain from offering jQuery advice. This script is created to display additional database records when you scroll down to the bottom inside a div named results-container. The issue I'm encountering is that the same data keeps appearing. I&ap ...

Error: JSON key data not present in rendering

Here is a JSON string I am working with: {"{\"nodeName\":\"abc\"}":[{"url":"abc","status":true},{"url":"abc","status":true}]," {\"nodeName\":\"pqr\"}":[{"url":"abc","status":true},{"url":"abc","status":true}]} ...

Negative vibes with for/in loop

My script is short and simple: hideElements = arguments.shift().split(','); for (iterator in hideElements) { console.log('--> hiding ' + hideElements[iterator]); lg_transitions({kind:"slide-up"}, {target: hideElements[iterat ...

Changing the location of an ArcGIS map with a click event in a Vue application

I am attempting to dynamically update a map to display my current location using Vue. I have created an onClick event that updates the props and sends them to my map component. To trigger a re-render of the map component when the data changes, I am utilizi ...

React Js month picker problem encountered

I am currently working on implementing a month picker using the library called react-month-picker The code is functioning correctly in React: https://codesandbox.io/s/react-month-picker-forked-84rqr However, when I tried to integrate the same code into a ...

What is the best way to assign a value to the param tag of an applet using JavaScript variables

This is my external javaScript file named myJs.js function search(){ var hint = document.getElementById("sChoice").value; var item = document.getElementById("sKey").value; document.getElementById("c").value=hint; document.getElementById ...

How do I assign a value to a multi-dimensional array in statically compiled Groovy?

I am working with a Groovy multi-dimensional array structure: boolean[][] arr = new boolean[10][10] In addition, I have defined a boolean variable: boolean value = true My next step is to assign the boolean value to an element in the array: arr[1][1] ...

How to deactivate an option in md-autocomplete

I encountered a scenario where I converted an md-input-container with a md-select/md-option to a md-autocomplete. While in the initial setup of md-select/md-option, we were able to apply ng-disabled property to both the md-select and md-option. However, wh ...

Simulated function for handling express functions

I'm currently working on a server.js file that includes an app.get function. To test this function using "jest", I am having trouble writing a mock function for the app.get implementation shown below. app.get('/api/getUser', (req, res) => ...

Exploring ways to retrieve nested values from JSON data using the Instagram API and Javascript

Trying to modify the script found at https://github.com/bigflannel/bigflannel-Instafeed in order to access Instagram photos on a website. Unfortunately, the script does not currently support displaying photo comments. I attempted to make modifications that ...