Arrange a javascript object by sorting it according to a date attribute

I am working with an array of objects that each contain a date property. My goal is to group together all the objects with the same date into separate arrays, creating as many arrays as there are unique date values. I am looking for the most efficient way to iterate over the array and organize it. I am open to using Angular array functions for this task.

Answer №1

To achieve the desired result, a combination of $filter and iterating through an array would be ideal. Let's illustrate this with an example:

//sample values
var objects = [{exampleProp: undefined, date:new Date(3,1,1970) }, 
              {exampleProp: undefined, date:new Date(2,1,1970)}, 
              {exampleProp: undefined, date:new Date(2,1,1970)}, 
              {exampleProp: undefined, date:new Date(1,1,1970)}];


//sort the master array by date property
objects = $filter('orderBy', objects, 'date')($scope);

//grouping the master object by date
var dictionary = {};
objects.forEach(function(object){
   if(dictionary[object.date] == undefined)
      dictionary[object.date] = [];

    dictionary[object.date].push(object);
});

//converting the dictionary to an array of arrays
var objectsByDate = [];
for(var date in dictionary)
  objectsByDate.push(dictionary[date]);

Refer to $filter and orderby documentation for more information on ordering by object properties.

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

The rejection of the WordPress custom plugin was due to the use of the reason 'Directly accessing core loading files'

I created a plugin for personal use and later decided to make it available to the public. However, my submission was rejected after a code review citing the reason ##Calling core loading files directly. I have addressed all the issues pointed out, except ...

Is it possible in Javascript to verify if a different script has been triggered?

I recently created a pop-out menu for a website using HTML and Javascript. The menu currently has a button that opens a div container with a close button inside it. While the buttons are functioning properly in hiding the div, the elements within the div d ...

The PDFKIT feature ensures that any overflowing data in a row is automatically moved to a new page

A function in my code generates a row of data based on an array. It works perfectly fine for the first page, but as soon as the data overflows somewhere around doc.text("example",70,560), it jumps to the next page. The issue arises when the Y coo ...

Is there a way to utilize code to invoke a method of an object? For example, calling MyObject.XVariable(//some function

I have a unique object that gets its data filled from an API call. let MyDog = { Name: 'Dog', } let arrayFunctions; fetchDogsFunctions(dogAPIUrl).then(res => { // The results variable contains an array of functions the dog can do, such as get ...

A reliable approach for dynamically altering SVG graphics

It seems like IE10 does not support CSS transformations for SVGs, only attribute transformations. Here is an example: <svg><rect id="myrect" width="200" height="200"></rect></svg> setTimeout(function() { var r = document.getE ...

Issue with rendering Rails View using Javascript

In my show.html file, I have an <a ng-click="writeReview(product)" class="vote-link">Review</a> link. Within my javascript file, I have the following code: $scope.writeReview =(product) -> $http.get("/products/#{product.id}/review/new" ...

A guide on elegantly pausing for the completion of .map() function and generating fresh keys within the array[index]

I am currently working on generating an array with the following values: { name: 'John', age: 35, employer: 'ABC', paycheck: 5,000, last_paycheck: 4,900, change: 100 } // new array and initializing the array with these initial values: ...

What is the most efficient method for sending query parameters through a URL in Vue.js with Axios?

My goal is to use Axios upon page load to retrieve a JSON object from the base URL. When a button is clicked, I want to append query parameters to the URL and fetch a different JSON object. For example, if the base URL is 'test.com', clicking the ...

What are the steps for implementing if-else statements in JavaScript when working with multiple dropdown lists?

I have encountered an issue while trying to display options in multiple drop-down lists. Only two words (CHENNAI AND IOS-XE, BANGALORE AND IOS-XR) are being displayed and the rest of the words are not appearing. Can someone provide assistance on fixing thi ...

Guide on changing the order of Vue sibling components when rendering a shared array within a parent component list

Currently facing a unique challenge and seeking input: Within the 'App', utilize 'TestListItem' for odd item indexes and 'TestListBetterItem' for even indexes. The same index must be used for both components. Initial attemp ...

Ajax loaded scripts are unable to access global variables

Index.html <script> let bar = 1; </script> This html page is being loaded multiple times on the page using AJAX: article.html <script> if (bar === 1) { // perform a task } // Error: bar is not defined </script> Bar is a simple ...

Dealing with performance issues in React Recharts when rendering a large amount of data

My Recharts use case involves rendering over 20,000 data points, which is causing a blocking render: https://codesandbox.io/s/recharts-render-blocking-2k1eh?file=/src/App.tsx (Check out the CodeSandbox with a small pulse animation to visualize the blocki ...

Transform the retrieved binary data into an object and then send it back

I have been working on a React function that fetches a .csv file stored in S3. The function reads the blob within the file, converts it to an object, and then returns it: import { Storage } from "aws-amplify"; import Papa from "papaparse&quo ...

Where can the Path be found for Json inside App Phonegap?

Having some trouble with my Phonegap App! Everything seems to be working fine when I test it in my browser. However, once I compile it into an APK and install it on my phone, it's unable to find the JSON data. I'm a beginner in programming and a ...

Is the top bar feature malfunctioning in version 4.3.2 of Foundation?

During my previous project, I utilized the open-source Foundation 4 framework and successfully implemented a top bar navigation. Now, as I embark on a new project with Foundation, I have downloaded the Foundation 4.3.2 version from . Despite referencing th ...

How to apply CSS styling to a specific element using jQuery

When using $(".className"), all elements with the class .className are returned. How can I target a specific element by its index number to apply styling only to that element? <html> <head> <script src="https://ajax.googleapis.com/ajax ...

jQuery Filter for Page Content - choose specific text within paragraphs and clickable links

I recently created a page search filter using Bootstrap 5, but it seems to only display text content and not any content enclosed within the a tags. You can check out the JS Fiddle link provided below for reference: https://jsfiddle.net/mfen723/rozy16pt/1 ...

Whenever I attempt to substitute a section of a numpy array, no changes seem to occur

I am working with the code snippet below currSub is a DataFrame containing 2850 elements, from which I extract timestamps numbered 1 to 2850 along with a vector of probabilities of the same length. My objective is to insert the currProb vector into the r ...

In the ajax call, an empty JSON array object is sent as the data

Utilizing JSON data as a parameter for an ajax call: var startDate = dateFormatForSave($("#start_date").val().trim()); var arrayOfStudentsInfo = []; var table = $("#selected_students"); table.find('tr').each(function(i, el) { var rowId = $( ...

What steps can I take to ensure that I establish the definition of this variable?

My situation involves a variable called Blog, which is a mongoose model. The definition of this variable is as follows: db.once("open", function(){ var userSchema = new mongoose.Schema({ username: String, password: String }); ...