Organizing month and year in angularjs: A step-by-step guide

I have a table with a column for month and year. I need to sort the dates by year. Can someone please help me with this? You can view the code in the provided fiddle.

In my case, the date format is "MMMM yyyy". For example, if I have "August 2016", "September 2015", and "January 2018", I want to sort them based on the year to get "September 2015", "August 2016", and "January 2018".

How can I achieve this in angularjs?

jsfiddle

   var app = angular.module('app', [])
       .controller('appController', appController);

   appController.$inject = ['$scope', '$window'];

   function appController($scope, $window) {

       $scope.title = "date sorting example";

       $scope.sortType = "name";
       $scope.sortReverse = true;

       var dateA = new Date("02/06/2016");
       dateA.setDate(dateA.getDate() + 2);
       var dateB = new Date("07/06/2017");
       dateB.setDate(dateB.getDate() + 4);
       var dateC = new Date("08/06/2016");
       dateC.setDate(dateC.getDate() + 7);
       var dateD = new Date("04/06/2018");
       dateD.setDate(dateD.getDate() + 20);

       $scope.allItems = [{
           date: dateA,
           name: "A"
       }, {
           date: dateB,
           name: "B"
       }, {
           date: dateC,
           name: "C"
       }, {
           date: dateD,
           name: "D"
       }];

   };
<div ng-controller="appController">

    <h1>This is my {{title}}</h1>
    <table class="table table-striped">
        <thead>
            <td data-ng-click="sortType = name; sortReverse = !sortReverse;">
                Date
            </td>
            <td data-ng-click="sortType = name; sortReverse = !sortReverse;">
                Name
            </td>
        </thead>
        <tbody>
            <tr ng-repeat="item in allItems">
                <td>{{item.date | date:"MMMM yyyy"}}</td>
                <td>{{item.name}}</td>
            </tr>
        </tbody>
    </table>

</div>

Answer №1

Be sure to utilize the Array.sort method for sorting arrays in JavaScript.

var dateA = new Date("02/06/2016");
dateA.setDate(dateA.getDate() + 2);
var dateB = new Date("07/06/2017");
dateB.setDate(dateB.getDate() + 4);
var dateC = new Date("08/06/2016");
dateC.setDate(dateC.getDate() + 7);
var dateD = new Date("04/06/2018");
dateD.setDate(dateD.getDate() + 20);

let allItems = [{date: dateA,name: "A"}, {date: dateB,name: "B"}, {date: dateC,name: "C"}, {date: dateD,name: "D"}];

allItems.sort((a,b) => a.date - b.date);

console.log(allItems);

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

Trouble with React Material Select Options Failing to Populate

After iterating and producing MenuItems, I am able to see the items when I console.log, but in the UI, the dropdown appears empty. I'm puzzled as to why the Select's are not being populated. Any thoughts on this issue? Below is the supplied code ...

Creating a Pop-Up on Website Load with HTML, CSS, and Jquery

<script> // utilizing only jquery $(document).ready(function(){ $('#overlay-back').fadeIn(500,function(){ $('#popup').show(); }); $(".close-image").on('click', function() { $('#po ...

The updating of input and output does not happen instantly; there is a delay before changes

Having an issue with updating input values in React. When using the setState method, the console log does not show the updated input value immediately. For instance, typing "a n" into the input only logs "a" after the second keystroke... Although I under ...

Can you provide a require statement that is the equivalent of this import statement?

Looking to transition a few files from utilizing import to using require in order to eliminate the need for Babel. One of the import statements appears like this: import React, { Component } from 'react'; How can I change it to a require state ...

Saving JSON Data into my HTML document

Currently, I am in the process of learning about API's at school which means my knowledge of jQuery is quite limited. However, I have a specific task that involves making an API call and using the retrieved information. Recently, I conducted an ajax ...

Enhancing the efficiency of a TypeScript-written file content parsing class

Seeking advice on optimizing a typescript module used by a VSCode extension. This module accepts a directory and parses the content within the files, which can be time-consuming for directories with a large number of files. To avoid copying the entire cla ...

A step-by-step guide on integrating AngularJS login with Spring Security

My goal is to implement a login functionality using AngularJS to send the username and password to Spring Security, instead of relying on the traditional login.jsp method. Below is an outline of my configuration: -security_config.xml <http use-express ...

React error: "Unable to locate property 'bind' within the undefined"

After reviewing several solutions, I'm still struggling to understand. Below is my code snippet: // userInputActions.js ... export function dummy() { console.log('dummy function called'); } ... // *userInputPage.js* import * as use ...

Recoil: Executing a function when an atom is modified

My goal is to store a user object in an atom and cache it in localStorage every time it changes to avoid having the user sign in repeatedly if the app crashes: localStorage.setItem('user', JSON.stringify(user)) Previously, with useContext, I ach ...

After being redirected from another page using history() in React, the state is initially set to null but later gets updated to the correct value - Firebase integration

After logging in and being redirected to the profile page, I encounter an error that says 'Unhandled Rejection (TypeError): Cannot read property 'email' of null'. How can I ensure that the state is set before proceeding with any additio ...

What could be the reason for the token being undefined on the client side?

I have built an ecommerce site using nextjs and mongoose, integrating a jwt token in a cookie for client-side authentication. However, when trying to retrieve the token from the cookie named OursiteJWT, I encountered issues with it being undefined: Despit ...

Spin an object around the global axis using the tween.js library

I'm trying to achieve a gradual rotation of a cube on the world axis using tween. Initially, I was able to rotate the cube around the world axis without tweening with the following code: rotateAroundWorldAxis(cube[1], new THREE.Vector3(0,1,0),degreeT ...

Having trouble updating the input value in AngularJS?

As I venture into customizing an AngularJS tutorial on a Saturn Quiz, I am transforming it from multiple choice to a fill-in-the-blank quiz. The challenge I face is that the first answer registers as correct or incorrect, but subsequent questions always s ...

The typescript MenuProvider for react-native-popup-menu offers a range of IntrinsicAttributes

Looking to implement drop-down options within a Flatlist component, I've utilized the React Native Popup Menu and declared MenuProvider as the entry point in App.tsx. Encountering the following error: Error: Type '{ children: Element[]; }' ...

Transferring form data from Jade to Node.js for submission

My Jade template includes the following form structure: form(action='/scheduler/save/' + project.Id, method='post') div.form-group label.control-label.col-md-2 RecurringPattern di ...

The scrollIntoView function is not functioning as expected

Having an issue with my function called scrollIntoView. It just refuses to work :( Take a look at the code below: HTML <section class="page_mission"> <div class="page_mission_text"> <div class="scroll-animations"> <di ...

Issue with Laravel 5.4: AJAX behaving unexpectedly and not returning errors as it should

After going through several tutorials on handling AJAX requests in Laravel, I'm still facing some issues. Each tutorial has its own approach... Finally, one method is not giving me a 500 error, but it's not displaying validation errors as expect ...

Updating the video tag's source attribute using JSON information

I am in the process of creating a unique video player using HTML and Javascript that will sequentially play a set of videos until all 6 have been displayed. The URLs for these videos are stored within an array that is mapped in a .json file named clips.jso ...

The Ajax POST call was unsuccessful

I seem to be encountering an issue, even though everything appears to be correct. I am currently developing on localhost and I am facing difficulties loading a file. This is the code I am using. I am working in NetBeans and the console shows no errors. & ...

How can we add up the sum with just one click and then display the

Is there a way to calculate numbers within specific DIV boxes and display the total in a separate DIV when a box is clicked? I've attempted different methods, including enclosing the code within the window.onclick function. Check out my code on this J ...