Sling Academy
Home/JavaScript/Filtering and Grouping Data by Day, Month, or Year in JavaScript

Filtering and Grouping Data by Day, Month, or Year in JavaScript

Last updated: December 12, 2024

One of the most common tasks in data processing applications is filtering and grouping data. In web applications, JavaScript is a powerful tool for these tasks. This article will guide you through filtering and grouping JavaScript data by day, month, or year using various approaches and functions.

Filtering Data Using JavaScript

Filtering is the process of transferring only certain parts of data based on specified criteria. In JavaScript, this is commonly done with the filter() method, which creates a new array filled with elements that pass the test implemented by the provided function. Below is a simple example:

const data = [
  { date: '2023-09-12', value: 34 },
  { date: '2023-09-13', value: 45 },
  { date: '2023-10-14', value: 56 },
];

const filteredData = data.filter(entry => new Date(entry.date).getMonth() === 8); // September

console.log(filteredData);
// Output: [{ date: '2023-09-12', value: 34 }, { date: '2023-09-13', value: 45 }]

In this example, we're filtering the data to find only the entries that have dates in September. Please note that months in JavaScript Date objects are zero-indexed. So, September is represented by 8.

Grouping Data by Day, Month, or Year

After filtering data, you often need to group them to provide meaningful insights. JavaScript doesn't have a built-in function for grouping data, but you can create a custom function for this purpose.

Grouping Data by Day

To group data by day, we will use the reduce() method. Here is how you can achieve it:

const groupedByDay = data.reduce((acc, current) => {
  const day = new Date(current.date).toISOString().split('T')[0];
  if (!acc[day]) {
    acc[day] = [];
  }
  acc[day].push(current);
  return acc;
}, {});

console.log(groupedByDay);
/* Output:
{
  '2023-09-12': [{ date: '2023-09-12', value: 34 }],
  '2023-09-13': [{ date: '2023-09-13', value: 45 }],
  '2023-10-14': [{ date: '2023-10-14', value: 56 }]
}
*/

The above script groups the data by the exact date. We convert the date to an ISO string to easily group entries sharing the same date.

Grouping Data by Month

Grouping by month follows a similar pattern, but you need to extract both the year and month:

const groupedByMonth = data.reduce((acc, current) => {
  const yearMonth = new Date(current.date).toISOString().slice(0, 7);
  if (!acc[yearMonth]) {
    acc[yearMonth] = [];
  }
  acc[yearMonth].push(current);
  return acc;
}, {});

console.log(groupedByMonth);
/* Output:
{
  '2023-09': [
    { date: '2023-09-12', value: 34 },
    { date: '2023-09-13', value: 45 }
  ],
  '2023-10': [{ date: '2023-10-14', value: 56 }]
}
*/

In this example, we slice the ISO string to include only the year and the month, effectively grouping entries that fall into the same month.

Grouping Data by Year

Finally, to group data by year, extract the year from the date string:

const groupedByYear = data.reduce((acc, current) => {
  const year = new Date(current.date).getFullYear();
  if (!acc[year]) {
    acc[year] = [];
  }
  acc[year].push(current);
  return acc;
}, {});

console.log(groupedByYear);
/* Output:
{
  '2023': [
    { date: '2023-09-12', value: 34 },
    { date: '2023-09-13', value: 45 },
    { date: '2023-10-14', value: 56 }
  ]
}
*/

Here, we retrieve the year using getFullYear() method, ensuring data is grouped into the correct year buckets.

Conclusion

By mastering filtering and grouping in JavaScript, you can effectively process data and draw deeper insights from your datasets. The examples provided in this article cover basic to moderate complexity, but the principles can be scaled and customized according to your needs. Always ensure your date parsing is correctly aligned with the format in which dates are stored to avoid potential errors in larger datasets.

Next Article: Transforming Date Inputs into Day Names (e.g., Monday) in JavaScript

Previous Article: Synchronizing Clocks Across Different Systems in JavaScript

Series: Date and Time in JavaScript: Basic to Advanced Tutorials

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration