Organize array by year and month groupings

I'm trying to organize an array of events by year and month. Here is a sample of my data:

const events = [
  {
    name: "event 1",
    year: 2021,
    month: 1,
  },
  {
    name: "event 2",
    year: 2021,
    month: 9,
  },
  {
    name: "event 3",
    year: 2021,
    month: 1,
  },
  {
    name: "event 4",
    year: 2022,
    month: 7,
  },
]

The desired outcome would be structured like this:

[
  {
    year: 2021,
    month: 1,
    events: [
      {
        name: "event 1"
      },
      {
        name: "event 3"
      }
    ]
  },
  {
    year: 2021,
    month: 9,
    events: [
      {
        name: "event 2"
      }
    ]
  }
]

I'm looking for the best method to achieve this task. I've come across some stackoverflow posts about grouping arrays by key value, but that's not quite what I need.

const groupBy = (array, key) => {
  return array.reduce((result, currentValue) => {
    // If an array already present for key, push it to the array. Else create an array and push the object
    (result[currentValue[key]] = result[currentValue[key]] || []).push(currentValue);
    // Return the current iteration `result` value, this will be taken as next iteration `result` value and accumulate
    return result;
  }, {}); // empty object is the initial value for result object
};

const groupedByYear = groupBy(events, 'year');

Answer №1

One way to achieve this is by using the combination of reduce and Object.values

const data = [
  {
    type: "data type 1",
    value: 100,
  },
  {
    type: "data type 2",
    value: 200,
  },
  {
    type: "data type 1",
    value: 300,
  },
];

const output = Object.values(data.reduce( (acc,data) => {
    const key = `${data.type}`;
    if(!acc[key]) {
      acc[key] = {type: data.type, values:[]}
    }
    acc[key].values.push( {value:data.value} );
    return acc;
},{}));

console.log(output);

Answer №2

To implement a more dynamic approach, consider using a combined key to group desired properties together.

Subsequently, eliminate all unnecessary keys in the grouping process and add a new object without those unwanted properties.

const
    events = [{ name: "event 1", year: 2021, month: 1 }, { name: "event 2", year: 2021, month: 9 }, { name: "event 3",  year: 2021, month: 1 }],
    keys = ['year', 'month'],
    result = Object.values(events.reduce((r, o) => {
        let value,
            key = keys.map(k => o[k]).join('|');

        if (!r[key]) r[key] = { ...Object.fromEntries(keys.map(k => [k, o[k]])), events: [] };
        
        r[key].events.push(keys.reduce((t, k) => (({ [k]: value, ...t } = t), t), o));
        return r;
    }, {}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Utilize npm to construct a Vue application and execute it on a Raspberry Pi device

My roommate and I are currently working on a Vue app project together, and we're aiming to deploy it on our Raspberry Pi. We're wondering if there's a way to npm build the final app on our PC and simply start the server on the Pi without hav ...

Trouble accessing state when React child calls parent method

Within my project, I am working with 3 components that are nested as follows: App->GameList->GameItem The App (parent) component has a method that is triggered by the onClick event within the GameItem (child) component Upon clicking the GameItem co ...

Learn the process of adding asynchronous middleware modules to your express.js application

I'm currently developing an express application that utilizes the node_acl module along with a MongoDB database. I have created a custom module that sets up and configures node_acl asynchronously. This middleware needs to be called as the second piece ...

Efficiently handling jsonwebtoken errors in node and express

Here is the verification function I've created: exports.verifyToken = function(req, res, next){ var token = req.body.token; jwt.verify(token, config.sessionSecret, function(err, decoded) { if(err){ return next(err); }else{ ...

Incorporated React component from Rails-assets.org into a Rails application

I have been trying to incorporate a react component from rails-assets.org into my Rails application. Currently, I am using the react-rails gem to write react view in my application. Now, I want to use other react components such as react-router, react-sel ...

Developing a Highchart Graph using JavaScript

I am trying to develop a high chart graph. Check out my code on FIDDLE LINK. I have two values, a and b, for the x-axis and y-axis. The issue arises when the difference between a and b is minimal, such as when both are equal (-9). In such cases, the grap ...

What is the process of decoding a URL in JavaScript?

Is there a better method to decode this URL in order to use it with JavaScript? URL: https://www.example.com/post.php?v=1&text=it's-me&20hello%0Aworld%0A At present, any occurrence of ' in the URL is causing an error and blank lines ar ...

Using Functional Programming with Node.js: A guide to waiting for a function to complete

As a newcomer to Node.js, I am satisfied with the syntax of JavaScript as I have utilized it for constructing web interfaces. With substantial experience in Object-Oriented Programming from Java and C#, along with an understanding of functional programming ...

Adding client-side scripts to a web page in a Node.js environment

Currently, I am embarking on a project involving ts, node, and express. My primary query is whether there exists a method to incorporate typescript files into HTML/ejs that can be executed on the client side (allowing access to document e.t.c., similar to ...

AJAX response for form validation

I need to validate my contact form when the submit button is clicked. If all fields are valid, I want to display a Processing message using AJAX, followed by a success message with the entered name. The content of my Form is: <form onsubmit="return va ...

What is the best way to utilize AJAX to upload several images in PHP?

I have a UI that looks like this: https://i.sstatic.net/BAbwP.jpg I am trying to upload multiple videos using ajax in PHP. I attempted to use FormData() in jQuery for this purpose. However, it seems to only upload one image and not more than that. Her ...

"Enhance user experience with Sweetalert 2's customizable sorting options for select inputs

Here is the code snippet that I am currently working with: this.getdata((params.....).then((data) => { var selectOptions = []; for (let i = 0; i < data.length; i++) { selectOptions[data[i].id_calc] = data[i].surname + " " + data[i ...

Angular Oops! We ran into a small hiccup: [$injector:modulerr]

I am facing an issue with an angular js error angular.js:36 Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.2.19/$injector/modulerr?p0=app&p1=Error%3A%20…gleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.19%2Fangular.min.js%3A18%3A139) ...

Dealing with Unreliable Data in Scatter Plots using React and HighCharts

Initially, I utilized line charts for my data visualization needs. However, I now require multiple data points on the same X-Axis with tooltips, which has led me to discover HighCharts behavior: "In a line chart, by default, Highcharts will display t ...

What is the process for creating a selector that links to an element that has been dynamically generated?

Can anyone help me figure out how to create a selector that links to a dynamically created element without using an event on the dynamic element? By dynamically created element, I mean an element that is not present in the HTML at the beginning. I know t ...

What is the proper way to utilize the setState() function in ReactJS?

I am new to the world of ReactJS and I have been exploring the concepts of state and setState(). While trying to implement a name change using setState(), I found myself wondering where exactly in my code should I invoke the setState() method: Should I c ...

What precautions should I take to safeguard my HTML/CSS/JS projects when sharing a link with my employer?

Picture this scenario: you need to share a link for your work, but you want to protect it from being easily copied or developed further by someone else. However, since it's a document, any browser can still view it. Can anyone recommend a tool that wi ...

Saving the AJAX response object in a global variable - Important fields are not being retrieved

Currently, I am developing an asynchronous webpage in Grails wherein I invoke a controller and display the response as a D3.js network. To ensure further usability, I saved the object as a global variable. Despite the successful execution of the function u ...

Vue Template ref Error: Unable to access scrollHeight property of null object

I'm currently working on creating a responsive sidebar in Vue, and I encountered an issue after refactoring my project to remove the state.js file. The problem is related to the dropdown/collapse elements, and it's throwing a TypeError: Cannot re ...

Angular.js and D3 - The Perfect Combination for Dynamic Data Visualization!

Having some trouble creating a chart with angular.js. The chart is not appearing on the page when using rout.js, but it works fine without it. Here's my code: var myapp = angular.module('myapp', ['angularCharts']); function D3 ...