"Implementing an Angular function to loop through an array and sort

My job involves handling an array of objects, each object containing various properties:

comments:""
id:1
inProgress:false
jobDescription:null
lastUpdateDate:"07/08/2016"
lastUpdatedByUser:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="641c1c1c240506074a070b09">[email protected]</a>"
product:"Chicken"
status:Object
templateName:"Standard Template"
uploadDate:"07/08/2016 10:36:01"

I need to implement a function in Angular that can iterate through the entire list and organize the objects based on their upload dates, with the most recent appearing first.

Although I attempted to achieve this using the following code, it did not produce the desired result:

vm.uploads = $filter('orderBy')(vm.uploads, vm.uploads[0].uploadDate, reverse);

Answer №1

Sorting Arrays using Array.prototype.sort can simplify your code:

myArray.sort(function(x,y){
   return new Date(x.dateCreated).getTime() - new Date(y.dateCreated).getTime();
})

To sort in descending order, swap x and y

Answer №2

You seem to have a syntax error, make sure to call it in this way:

vm.uploads = $filter('orderBy')(vm.uploads, 'uploadDate', true)

Take a look at this example demo:

(function() {
  angular
    .module('app', [])
    .controller('MainCtrl', MainCtrl);

  function MainCtrl($filter) {
    var vm = this;

    vm.reverse = false;
    vm.uploads = [  
       {  
          "comments":"",
          "id":1,
          "inProgress":false,
          "jobDescription":null,
          "lastUpdateDate":"07/08/2016",
          "lastUpdatedByUser":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7800000038191a1b561b1715">[email protected]</a>",
          "product":"Chicken",
          "status":1,
          "templateName":"Standard Template",
          "uploadDate":"07/08/2016 10:36:01"
       },
       {  
          "comments":"",
          "id":2,
          "inProgress":true,
          "jobDescription":null,
          "lastUpdateDate":"08/08/2016",
          "lastUpdatedByUser":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="750d0d0d351417165b161a18">[email protected]</a>",
          "product":"Horse",
          "status":1,
          "templateName":"Custom Template",
          "uploadDate":"08/08/2016 12:49:05"
       }
    ];

    vm.order = function () {
      vm.uploads = $filter('orderBy')(vm.uploads, 'uploadDate', vm.reverse = !vm.reverse);
    }
  }
})();
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
</head>

<body ng-controller="MainCtrl as main">
  <ul>
    <li ng-repeat="upload in main.uploads track by $index" ng-bind="upload.uploadDate"></li>
  </ul>
  <hr>
  <button type="button" value="order" ng-click="main.order()">Change order</button>
</body>

</html>

I suggest checking the documentation.

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

Can a JavaScript string be converted into a date format for insertion into a SQL database?

I'm currently developing a bot and facing an issue where I need to make it upload two dates. However, the arguments it can have are numbers within strings. For example, I have two strings '08222020' and '10282022,' which I need to ...

What is the process for creating an image with AJAX jQuery while it is still loading?

I am trying to create an image that shows the ongoing download process as Page (2014.php) loads. I want to display a waiting gif during this time: My code example is not functioning correctly! I need to show a waiting image while my page (2014.php) takes ...

Trouble altering material of object using keypress in three.js

I have been attempting to assign colors from an array to my object when a key is pressed, but I am only able to access the first element of the array. Is there another method that could be used for this purpose? One approach I considered was using a rando ...

Exploring the possibilities with Node.js and OpenCV

I'm experiencing difficulties with face tracking and detection using the npm opencv package. Right now, I'm attempting to draw a circle around each detected face. Below are the error details and associated files. I'm unsure if it's a b ...

Enhance the multi-level structure of a mongoDB schema

This is an example of my model schema { "_id" : ObjectId("59999454bad567268f78dc09"), "chapters" : [ { "_id" : ObjectId("59999454bad567268f78dc0a"), "individualChapters" : [ { "_id" : ObjectId("59999454bad ...

I am getting text content before the input element when I log the parent node. What is causing this issue with the childNodes

Does anyone know why 'text' is showing up as one of the childNodes when I console.log the parent's childNodes? Any tips on how to fix this issue? <div id="inputDiv"> <input type="text" id="name" placeholder="Enter the nam ...

Updating the User Interface in ReactJS based on changes in the state

I am relatively new to ReactJS and I am currently working on building a Sudoku Solver. My goal is to update the state in real-time so that the user can visually see how the algorithm is progressing. However, my current code only updates the UI at the end ...

The function array.push() is not achieving the intended outcome that I had in mind

Currently facing a rather frustrating issue. I'm attempting to utilize D3.js for dynamically plotting data (specifically, scores of individuals). Retrieving record data from a firebase database whenever changes occur - this is represented by an obje ...

Learn the method for showing and hiding a div element in AngularJS

There is a loader on my screen that stays visible until the page finishes loading or encounters an error. Within a div, I have the loader... <div id:loader class="loading"> ...and I want to toggle its visibility based on the page loading status. ...

Chrome and Firefox: Images cling together

I've encountered an issue with my recently launched website. Some images in a grid appear to be stuck together, but this problem only occurs in Firefox and Chrome browsers. Oddly enough, zooming in to around 110% then back to 100% seems to temporarily ...

Unable to locate Require.js

I have an old browser application with a few dependencies that need to be migrated to TypeScript. In order to do this, I included the following in my app.ts file and compiled it against ES6 with AMD (I believe AMD is suitable for browsers): import * as L ...

What is the benefit of validating both the post request and the database schema on the backend?

Question: Is it necessary to use express-validator for data validation when mongoose schema can handle it? As a front end developer, I normally perform form validation before submission. Recently, I have been exploring express. Initially, I utilized a li ...

Ways to transfer information from a function within one element to another element

I have two components: one that logs the indexes of a carousel and I need to pass these indexes into the second component. First Component <template> <div class="container container--white"> <Header /> <carousel-3d @a ...

Error: JSON parsing failed due to an unexpected token 'S' at position 17

Trying to troubleshoot a syntax error in JSON.parse() within a product warranty registration process. Transitioning from Java to AngularJS for this project, I have an API built in PHP handling the back-end operations and a controller managing communication ...

What is the reason for certain elements being grouped in an array, while others are not?

Update: Special thanks to deoD for guiding me to the correct resource - this post is actually a duplicate of Angularjs minify best practice I can't help but feel that this is a rather straightforward matter, but sadly I lack the terminology and my at ...

Eliminating redundancies within a collection of numPy arrays

I am facing a challenge with an ordinary Python list containing numPy arrays of the same shape and size. Some of the arrays in the list are duplicates, making it difficult to remove them due to the nature of numPy arrays. • The use of set() is not possi ...

Utilizing jQuery UI Slider for Calculating Percentage

I recently worked on an example where I incorporated 5 sliders, which you can see here: Example: http://jsfiddle.net/redsunsoft/caPAb/2/ My Example: http://jsfiddle.net/9azJG/ var sliders = $("#sliders .slider"); var availableTotal = 100; ...

The controller in Angular uses the $scope symbol _

App.controller('todoController', function ($scope) { // create a message to display in our view $scope.todos = [{ name: 'angular', done: false }]; $scope.clearTodo = function () { $scope.todos = _.filter($scope.tod ...

Is resizing possible using the Canvas identifier?

Is it possible to adjust the canvas size to match the width of the page using the canvas id's style in the html? Then in your javascript code for the canvas, can you have resize listeners that are responsive to the canvas size at any given time? I c ...

Which specific event in NextJS is triggered only during the initial load?

I am working on a NextJS app and I want to implement an initial loading screen that only appears during the first load. Currently, the loading screen pops up not only on the initial load but also whenever a link is clicked that directs the user back to the ...