Categorize a collection of objects based on shared characteristics

I am in need of the count for the current week only. Specifically, I want to calculate monthly totals with a breakdown per week. Currently, I can retrieve the weekly count for each month. Now, my goal is to display only the existing weeks. For example, if May has values for week 1 and week 2, I want to see the counts only for week 1 and week 2 under the month of May. Similarly, for July, I only want to display the counts for week 1 and week 3.

const response=[
  {
    "UserName": "User1",
    "week": "Week 1",
    "Type": "type3",
    "months": "May",
    "count": 2
  },
  {
    "UserName": "User1",
    "week": "Week 2",
    "Type": "type1",
    "months": "Jun",
    "count": 1
  },
  ...
];
const WEEKS = ["Week 1", "Week 2", "Week 3", "Week 4"];
const result = response.reduce((acc, obj) => {
    existingObj = acc.find(ele => ele.UserName == obj.UserName && ele.month == obj.months && ele.Type == obj.Type)
    if (existingObj) {
        ...
    } else {
       ...
    }
    return acc;
}, []);

console.log(result);

Expected Output:

[{"UserName":"user1","month":"May","Type":"Type3","Week1":2,"Week3":3},
          {"UserName":"user2","month":"May","Type":"Type3","Week1":2},
          ...
         ]

Answer №1

For the purpose of organizing records in the source array based on the UserName and month properties, you can create a Map (using Array.prototype.reduce()) with a composite key (consisting of UserName and month) and the corresponding grouped object value. Then, extract those objects into an array using Map.prototype.values():

const src = [{"UserName":"User1","week":"Week 1","Type":"type3","months":"May","count":2},{"UserName":"User1","week":"Week 2","Type":"type1","months":"Jun","count":1},{"UserName":"User1","week":"Week 1","Type":"type2","months":"Jun","count":1},{"UserName":"User1","week":"Week 2","Type":"type1","months":"May","count":1},{"UserName":"User1","week":"Week 3","Type":"type2","months":"July","count":1},{"UserName":"User2","week":"Week 1","Type":"type3","months":"May","count":2},{"UserName":"User2","week":"Week 2","Type":"type1","months":"Jun","count":1},{"UserName":"User2","week":"Week 1","Type":"type2","months":"Jun","count":1},{"UserName":"User2","week":"Week 2","Type":"type1","months":"May","count":1},{"UserName":"User2","week":"Week 1","Type":"type2","months":"July","count":1}],

      result = [...src
        .reduce((r, {UserName, week: w, Type, months, count}) => {
          const key = UserName+"\ud8ff"+months,
                week = w.replace(' ', ''),
                grouppedRecord = r.get(key)
          grouppedRecord ?
          Object.assign(grouppedRecord, {[week]: count}) :
          r.set(key, {UserName, Type, month: months, [week]: count})
          return r
        }, new Map)
        .values()
      ]
      
console.log(result)
.as-console-wrapper{min-height:100%;}

Answer №2

Begin by narrowing down your search criteria, and then iterate through the results using the filtered data as a reference.

For example, filter out all weeks in May and utilize that information for subsequent tasks.

var selectedWeeks = response.filter(function(item) {
    return (item.month === "May") && (item.user === "User1");
});

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

Obtain the URL of the parent window from a modal dialog using JavaScript

What is the proper syntax for obtaining the URL (specifically, the PATH) of the parent window from a modal dialog box in Internet Explorer. I have attempted several variations such as: window.opener.document.location window.opener.location this.opener.do ...

Update the nested radio button to a new value

I have a series of radio button lists generated using ng-repeat. I've managed to capture the selected item successfully. Now, I am attempting to set the default value for the radio buttons. Could someone please provide assistance? Below is my code sni ...

jQuery menu fails to toggle the class name

The toggle functionality in the Menu is not working properly. Upon clicking the toggle button, I encountered the following JavaScript error: "message": "Uncaught TypeError: Cannot read property 'toggle' of undefined", "filename": "https://st ...

What is the best way to limit a slash command to only be accessible to those with specific roles on a Discord server?

I am currently working on a discord bot using Discord.js V14 and implementing a command called "claimticket". However, I am facing an issue where I need to restrict this command to only members who possess one of the two specific roles that I have mentione ...

Gracefully Switching Between Various Functions

Suppose I have a collection of functions that perform various tasks: function doSomething() { console.log('doing something'); } function accomplishTasks() { console.log('accomplishing tasks'); } function executeAction() { console. ...

What are the capabilities of an INNER JOIN query in Objection JS?

Here is the data model that I am working with: https://i.stack.imgur.com/g1T5i.jpg In this model, a User can be associated with multiple Projects, and a Project can have many Users. These relationships are managed through a join table called UserProjects. ...

Extension ConfirmButtonExtender

There is a scenario where I need to skip the ConfirmButtonExtender based on the value of another field in the page. Typically, when a user clicks on my "Cancel" button, a modal popup appears using the confirmbuttonextender and the modalpopupextender. The ...

Internet Explorer 11 and the process of URL encoding

Hello there! I am currently working on an MVC project with Angular where I am utilizing a JsonResult to return JSON data from a list containing emails with a specific date. Below is the AJAX call I'm making from Angular: myApp.service('mailServ ...

Creating Accurate JSON-LD Schema and Object Instance

, I am in the process of developing a graph database to describe power systems using JSON-LD for the first time. Here are the steps I've taken so far: - Created a schema following the guidelines provided in this documentation. - Saved the schema to t ...

Check if the browser is compatible with the FREEZE and RESUME lifecycle events

Is there a method to determine if a browser is capable of registering the freeze and resume lifecycle events? Even after checking with Modernizr, a reliable JS library, it appears that these events are not supported. Although extremely beneficial, Safari ...

Issue: The jQuery function with the ID jQuery1830649454693285679_1359620502896 did not receive a JSON

After going through numerous Q&As on the same problem, I couldn't find a solution specific to my issue. The situation involves a PHP script that outputs a JSON string: header('Content-Type: application/json'); echo $result; Here is th ...

Unable to modify a variable within a request

Having trouble updating a variable within a request? It seems like the variable doesn't change when it should. const request = require("request"); var all = JSON.parse(body); var steamplayer = all['response']['players']['play ...

I'm having difficulty retrieving an object from a JSON array

Link to JSON Data How can I retrieve all instances of actor objects from the JSON? private void parseJSON() { String url = "https://api.github.com/events"; final JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, ...

What is the best way to retrieve the innerHTML content of an anchor tag with Cheerio?

Looking to extract data from an HTML page, a simplified example is provided below. Upon running the code, I anticipate the output to be [ "foo", "baz", "quux", ] but instead encounter an error message stating "TypeError: anch ...

Tips for maintaining a marker at the bottom of the screen while zooming, similar to Google Maps

Is there a way to customize the zoom behavior in my project? I want to maintain the bottom position while resizing the other three directions, and also include pitch adjustments. https://i.sstatic.net/hQdg8.gif https://i.sstatic.net/m3xef.gif I aim for t ...

Interactive tabs displaying real-time information

My goal is to create tabbed content based on a tutorial I found online. Following the tutorial step by step works perfectly, but now I want to take it a step further and make the tabs dynamic. The issue arises when some tabs have no content, so I need to g ...

"Facing rendering issues with handlebars.js when trying to display an

I have been diligently working on trying to display an array from my running express app, but despite the lack of errors, nothing is being rendered. Take a look at my handlebars template: <h3>Registered Users:</h3> <h5>{{users}}</h5& ...

Issues with simple jquery and javascript: unable to add the class ".has-error" and onclick event not properly defined

Currently, I am working with jQuery version 2.1.4 and JavaScript to implement a straightforward form validation using Bootstrap. During this process, I have encountered three peculiar issues. While I am confident that my jQuery code is properly functi ...

What method can I use in webpage coding to achieve this special highlight effect, and what is the official term for it?

Need help figuring out how to make an icon change from blue to white when selected. I've searched through Bootstrap, CSS, and HTML, but haven't found the solution yet. Any suggestions would be appreciated! https://i.stack.imgur.com/RK1PD.png ...

Troubleshooting the importing of external data to a D3.js tree diagram

Can anyone provide assistance with debugging my script? I am experiencing difficulties loading external data from a JSON file. The script works fine when the data is stored in a variable within the code, but not when it is separated into a file. <!DO ...