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

Retrieving data from a remote PHP server using JavaScript

I am currently working on two separate websites. Site A is coded using only HTML and JavaScript, while site B utilizes PHP. I am trying to figure out a way to access variables from site B within site A. For example: The code for site A looks something li ...

When using a function linked to an API request, an uncaught TypeError is thrown: Unable to access the 'includes' property of an undefined value

Utilizing the movie DB API (), I am displaying the results of my call on my page using Vue. The API supplies all the necessary data for me to achieve my objective, as demonstrated in this image https://i.stack.imgur.com/vP4I2.jpg Beneath each show's ...

Error message: "The contract is not defined in thirdweb-dev/react

I am currently using thirdweb-dev/react library to interact with a smart contract. However, I am encountering an issue where the contract is showing up as undefined in my code along with the following error message: query.ts:444 Error: Could not ...

How can you preselect an item in Vuetify's item group?

When attempting to preselect an item from a vuetify item-group, I discovered that it works with strings but not with objects. The vuetify documentation shows using a string array as the item list for the item-group, which functions correctly. However, whe ...

What is the reason onbeforeunload does not fire requests in Safari browser?

Is there a way to ensure that data is saved to the database when a user interacts with the page and also when they refresh it? I have tried using onbeforeunload event, but Safari does not wait for the server request to finish before reloading the page, c ...

Encountering Routing Issues in Express.js Following Passport.js Authentication

My authentication setup with Passport.js is pretty straightforward. After the user successfully authenticates, I redirect them to /work like this. app.post('/login', passport.authenticate('local', { successRedirect: '/ ...

Importing Vue and Vuex modules from separate files

Recently, I encountered an uncommon issue. I decided to keep my main.js and store.js files separate in a Vue project. In the store.js file, I imported Vuex, set up a new vuex store, and exported it. However, when importing this file into main.js and settin ...

Switch the paper tab to a dropdown menu in Polymer.js

Can someone assist me in transforming the paper tab into a paper drop down menu in polymer JS? I want the drop-down to appear with a list of values when hovering over the Top menu. Activity Execution <paper-tab cla ...

Navigational issues while incorporating path.join with __dirname in node.js

Can you clarify the distinction between using path.join(__dirname, "src/js") and simply __dirname + "src/js") in a node.js environment? ...

"Converting domain names with punycode and utilizing Firebase for a

My current project involves updating a Firebase app with NextJS, and I've encountered an issue that needs to be resolved. Upon running the command: % npm run build I received the following message: (node:3719) [DEP0040] DeprecationWarning: The `pun ...

Capture element in Javascript with screenshot functionality

I've been trying to save an image on my local website, but most of the code examples I find are for C# and Java, which I am struggling to convert to JavaScript. Many of the examples I come across use libraries like Point and IO that are not available ...

Ways to remove all HTML elements from a string

Check out the code that I currently have: I am looking for a way to prevent users from entering any HTML tags in the "Add Responsibilities" field. For example, if a user enters the following: <div>Test</div> It should only display the text l ...

Exploring the application of javascript method within a Vue template

Currently, I am attempting to extract a numeric value from the end of a URL. However, I am encountering an error in doing so. It has been a while since I last worked with Vue, but I know that we can use methods/functions to achieve the desired outcome. Cou ...

Utilize the power of Facebook login in your Parse client side application by integrating it with the user object

Currently, I am in the process of implementing a login system using both the Parse and Facebook Javascript SDK. While I have successfully implemented authentication on the client side, I am now facing the challenge of accessing the user object (generated ...

Add the file retrieved from Firestore to an array using JavaScript

Trying to push an array retrieved from firestore, but encountering issues where the array appears undefined. Here is the code snippet in question: const temp = []; const reference = firestore.collection("users").doc(user?.uid); firestore .collec ...

Printing the selected value from a drop-down box in HTML with JavaScript

I'm in the process of creating a web page structured like this: <html> <head> <title>Bug UI</title> </head> <body> <script> function myfunc() { //what should I include here?? } </script> <form> ...

After zooming in on the canvas and panning, I encountered a problem where I was unable to drag objects within the canvas. Instead, the canvas continued to pan as I tried to move the objects

1) I have the ability to pan the canvas and drag images without scaling or zooming. 2) When scaling or zooming, I can still drag images within the canvas. 3) However, if I try to pan the canvas after zooming and then attempt to drag images, only the canv ...

Learn how to dynamically chain where conditions in Firebase without prior knowledge of how many conditions will be added

Currently, I am working on a project using Angular and firebase. My goal is to develop a function that can take two arguments - a string and an object, then return an Observable containing filtered data based on the key-value pairs in the object for a spe ...

PHP - Utilizing an array to structure the presented information

Currently, I have an array named $socialMeta that looks like this: Array ( [0] => Array ( [socialFacebook] => Array ( [0] => http://www.facebook.com/someUsername ) ) [1] => Array ( [socialYoutube ...

An issue has arisen when trying to fetch and parse data using React and JavaScript

I am currently facing some challenges with fetching data from an API and displaying it using React. I have encountered errors and I am struggling with parsing the JSON response from the API. I believe that converting the response into an array may help res ...