Create groupings within an array based on the month and year using JavaScript

I am working with an array that looks like this:

var v = ["07/27/2015", "07/28/2015", "08/29/2015", "08/29/2015", "07/27/2016"]

My goal is to dynamically sort this array into a new empty array nv. Once sorted, nv should look like this:

var nv = [["07/27/2015", "07/28/2015"], ["08/29/2015", "08/29/2015"], ["07/27/2016"]]

I'm wondering if it's possible to achieve this type of sorting?

Answer №1

const dates = ["07/27/2015", "07/28/2015", "08/29/2015", "08/29/2015", "07/27/2016"];

const groupedDates = dates.reduce((accumulator, currentValue) => {
    const keyParts = currentValue.split("/");
    const key = keyParts[2] + keyParts[0];

    if (typeof accumulator[key] === "undefined") {
        accumulator[key] = [];
    }

    accumulator[key].push(currentValue);

    return accumulator;
}, {});

const result = Object.keys(groupedDates)
                    .sort((a, b) => Number(a) - Number(b))
                    .map((key) => {
                        return groupedDates[key];
                    });

console.log(result);    // [["07/27/2015","07/28/2015"],["08/29/2015","08/29/2015"],["07/27/2016"]]

live demo

Answer №2

I developed a function that organizes dates into an object with properties representing the month and year. Each date is assigned to the corresponding property based on its month and year. The function then generates an array and creates inner arrays for each property of the function. Within each inner array, all dates belonging to that property are stored. This method proved to be more effective than using nested for loops.

// The function accepts an array of dates formatted as MM/DD/YYYY
// It returns an array with nested arrays containing dates from the same month and year
var groupDates = function(dateArray) {
    // Initialize an object to sort dates by month and year
    var dateHash = {};
    // Array to hold the output
    var groupedDates = [];

    // Iterate over each date in the dateArray
    dateArray.forEach(function(currentDate) {
        // Check if there are other dates with the same month and year in the dateHash object
        if (dateHash[currentDate.substr(0, 2) + currentDate.substr(6)]) {
            // If other dates exist, add the current date to the array in the corresponding dateHash property
            dateHash[currentDate.substr(0, 2) + currentDate.substr(6)].push(currentDate);
        } else {
            // Create a new property for the month and year of the current date, and store the date in an array within that property
            dateHash[currentDate.substr(0, 2) + currentDate.substr(6)] = [currentDate];
        }
    });

    // Push the arrays of dates into the groupedDates array for each property in the dateHash
    for (var dateGroup in dateHash) {
        groupedDates.push(dateHash[dateGroup]);
    }
    return groupedDates;
};

var dateArray = ["07/27/2015", "07/28/2015", "08/29/2015", "08/29/2015", "07/27/2016"];
console.log(groupDates(dateArray));

Answer №3

To efficiently organize the array, one approach is to iterate through each value and determine if it belongs to a new month and year or if it already exists in the sorted array. Here is an example of how this could be achieved (keep in mind that this code has not been tested):

var updatedArray = [];
for(var index = 0; index < originalArray.length; index++){
    var currentDate = new Date(originalArray[index]);
    var monthAndYear = currentDate.getMonth() + "/" + currentDate.getFullYear();
    if(typeof(updatedArray[monthAndYear]) == 'undefined'){
         updatedArray[monthAndYear] = [];
    }
    updatedArray[monthAndYear].push(originalArray[index]);
} 

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

What is the process for deselecting text from a text field?

After performing a search and displaying the results on my search form, I've noticed that the text query in the textfield is being marked as selected text even though I don't want it to be. How can I prevent this? Fiddle 1) What is the best app ...

Converting Typescript library into a standalone global JavaScript file

Currently working on developing a Typescript library that follows this structure: https://i.stack.imgur.com/YyCHk.jpg This includes the following files: restApi.class.ts import { restApiOptions } from '../models/rest.options.model'; import { ...

"Troubleshooting the issue of AngularJS $http patch request failing to send

The information is successfully logged in the console when passed to replyMessage, but for some reason, the API does not seem to be receiving the data. Is the input field perhaps empty? replyMessage: function(data) { console.log(data); ...

An npm list is always full of modules

As I prepare to install a package using npm, I noticed that my folder for the new project already has numerous items listed when I run npm list. Is it normal for the folder not to be empty at this stage? Have I made an error somewhere? ...

Document: include checksum in HTML

I have a set of three files. The file named loader.js is responsible for creating an iframe that loads another file called content.html, which in turn loads content.js. I have made loader.js publicly available so that other users can include it on their ow ...

How can we best store the component's state in the URL in AngularJS?

I am working with a reusable widget that has its own state. This state includes the content of the search bar (2), one or more select boxes (1), and the tree where the user can pick the currently active element (3). My goal is to create a locationManager ...

Error: The TVJS Framework encountered a JSON Parse issue due to an unexpected EOF

I am currently developing a TVML application specifically for Apple TV. However, when I attempt to execute this code to send a request to a remote server, I encounter the following error: SyntaxError: JSON Parse error: Unexpected EOF. My goal is to run thi ...

Is there a possibility of Node.js being blocked during the processing of large file uploads?

Is it possible for Node.js to become blocked during the processing of large file uploads? Due to Node.js having only one thread, is there a risk that other requests will be blocked while handling large file uploads? If this is the case, what is the best ...

Dealing with a Nodejs/Express and Angular project - Handling the 404 error

Recently, I decided to dive into learning the MEAN stack and thought it would be a great idea to test my skills by building an application. My goal was simple: display a static variable ('hello') using Angular in the HTML. However, I ran into an ...

Determine whether an element in an array already exists in Java

Simple question: How do you determine if an (int) array entry, array[i], has already been assigned? This is part of a dynamic programming task, where results for sub-tasks are stored in an array that is continuously filled. I attempted: if(a[i] != null) ...

Adjust the size and orientation of an image according to the dimensions of the window and the image

As I delve into HTML and Javascript, I am facing a challenge with resizing an image based on the window size. The goal is for the image to occupy the entire window while maintaining its aspect ratio during resizing. Additionally, if the window size exceeds ...

Encountering error while attempting POST request in POSTMAN - "Unable to modify in restricted editor."

I'm facing a bit of a dilemma here. I can't seem to figure out how to make my editor in Postman stop being read-only. Can anyone lend a hand? Whenever I try to send a Post Request, my editor just won't cooperate and stays in Read-Only mode. ...

Designing Buttons and Titles for the Login Page

I'm currently working on developing a straightforward login page in react native and I've encountered some difficulties with styling. Does anyone have tips on how to center the text on the button? Also, is there a way to move the INSTARIDE text ...

Is it possible to integrate Processing JS on top of an HTML element?

I have currently integrated Processing JS with the HTML canvas element on a website. The goal is to have the Processing JS animation run smoothly over the existing HTML elements on the page. You can check out the site at [usandthings.com][1] to get an idea ...

Utilizing Core-TransitionEnd in Polymer: A Beginner's Guide

After a ripple animation on an item has executed, I would like to run a function. Currently, I am using the following code: <post-card id="card1"> <img width="70" height="70" src="../images/start.png"> <h2>P ...

How can the 'Read more' feature be modified to impact multiple boxes? (Using jQuery, JS, and CSS)

I am trying to add a 'Read more' feature on my friend's website. I was able to achieve the desired effect, but when I tried to adjust the alignment of the box, it affected the 'Read more' feature. Original design: https://codepen. ...

Is it possible to switch the linter in grunt.js to jslint instead?

Is it feasible to switch the linter used by grunt.js from jshint to jslint, considering that I am more accustomed to using jslint over jshint as the default linter? ...

The utilization of the "notFound" prop within getStaticProps does not influence the HTTP status code returned by the page

I recently set up a fresh Next.js application and created the following page: // /pages/articles/[slug].js import React from 'react' import { useRouter } from 'next/router' import ErrorPage from 'next/error' const Article = ...

Anticipating the resolution of the $rootScope value in Angular before the page is fully loaded

I've encountered an issue while using ngView with a static navigation bar that persists throughout the application: <div ng-include="'views/nav.html'" ng-controller="NavCtrl"></div> <div class="container-fluid" ng-view=""> ...

Error encountered while using Chart.js with JSON dataset

Struggling to make this work... Here are the necessary scripts: <script src="Chart.js"></script> <script src="jquery-1.11.3.min.js"></script> This is the full code I am working with: <body> <div id="chartCanvas"> &l ...