Arranging Arrays in an Object by Date Using Vue and JavaScript

I am currently working with an Object Structure similar to this:

{
  1000: [{AnnouncementCode: 1000, Name: 'foo', created_at: "2022-02-01T19:52:01.000000Z"},{AnnouncementCode: 1000, Name: 'foo', created_at: "2022-02-01T19:52:01.000000Z"},{AnnouncementCode: 1000, Name: 'foo', created_at: "2022-02-01T19:52:01.000000Z"}],
  2000: [{AnnouncementCode: 2000, Name: 'foo', created_at: "2022-02-01T19:52:01.000000Z"},{AnnouncementCode: 2000, Name: 'foo', created_at: "2022-02-01T19:52:01.000000Z"},{AnnouncementCode: 2000, Name: 'foo', created_at: "2022-02-01T19:52:01.000000Z"}],
  3000: [{AnnouncementCode: 3000, Name: 'foo', created_at: "2022-02-01T19:52:01.000000Z"},{AnnouncementCode: 3000, Name: 'foo', created_at: "2022-02-01T19:52:01.000000Z"},{AnnouncementCode: 3000, Name: 'foo', created_at: "2022-02-01T19:52:01.000000Z"}],
  4000: [{AnnouncementCode: 4000, Name: 'foo', created_at: "2022-02-01T19:52:01.000000Z"},{AnnouncementCode: 4000, Name: 'foo', created_at: "2022-02-01T19:52:01.000000Z"},{AnnouncementCode: 4000, Name: 'foo', created_at: "2022-02-01T19:52:01.000000Z"}]
}

Currently I have displayed all the values in the frontend, but they are sorted within each array separately and not globally.

I am looking for suggestions on how to efficiently sort all values from every key based on the 'created_at' date field.

Answer №1

In my opinion, sorting data like this may not be necessary, especially if it will mainly be used for mapping purposes. Instead of sorting, you can simply have an array of objects structured like this:

const array = [
  {AnnouncementCode: 4000, Name: 'foo', created_at: "2022-04-01T19:52:01.000000Z"},
  {AnnouncementCode: 4000, Name: 'foo', created_at: "2022-07-01T19:52:01.000000Z"},
  {AnnouncementCode: 3000, Name: 'foo', created_at: "2022-05-01T19:52:01.000000Z"},
  {AnnouncementCode: 1000, Name: 'foo', created_at: "2022-09-01T19:52:01.000000Z"},
  {AnnouncementCode: 2000, Name: 'foo', created_at: "2022-01-01T19:52:01.000000Z"},
  {AnnouncementCode: 1000, Name: 'foo', created_at: "2022-02-01T19:52:01.000000Z"},
]

// Sorting options
const sortedByDate = array.sort((a,b) => {
  if (a.created_at > b.created_at) return 1
  if (a.created_at < b.created_at) return -1
  if (a.created_at == b.created_at) return 0
})

const sortByAnnouncementCode = array.sort((a,b) => {
  if (a.AnnouncementCode > b.AnnouncementCode) return 1
  if (a.AnnouncementCode < b.AnnouncementCode) return -1
  if (a.AnnouncementCode == b.AnnouncementCode) return 0
})

const sortByCodeThanDate = 
  array
  .filter((data) => data.AnnouncementCode === 1000)
  .sort((a,b) => {
    if (a.created_at > b.created_at) return 1
    if (a.created_at < b.created_at) return -1
    if (a.created_at == b.created_at) return 0
  })

console.log(sortByCodeThanDate)

If sorting is absolutely necessary for the specific data you have provided, it might require more effort. The complexity of the task depends on whether the data is dynamic or not.

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

.li click event not triggering after appending to DOM

When I add an li element to a ul using jQuery, it looks like this: $(".vocab-list").append( $('<li onclick="play_sound(\''+val['audioURL']+'\');" class="vocab-word" id="vocab_' + val['id']+ &a ...

Incorporating outside content into HTML

Currently, I am working on a project at my job which requires me to create a comprehensive help file with multiple chapters and extensive text all within one large HTML file. However, as the text will need to be translated into different languages, I am lo ...

Guide to linking audio to MediaStream using Three.JS AudioContext

I have a MediaStream created from a canvas and I am trying to add audio to it from the Three.js audio stream. After attempting various methods, I found that the most concise solution is shown in the code snippet below. The stream seems to be added success ...

What is the best way to update input elements within a session using Vue.js?

Upon opening the input screen, the input items are populated with session information. However, when jQuery switches display based on the input item's value, it refers to the initial value in the program rather than the session information. This sugge ...

Sending data twice with jQuery AJAX to PHP

I implemented a standard JavaScript countdown timer that triggers an AJAX request to save data in a database once the countdown finishes. However, I've noticed that the entry is being saved twice. Any insights on why this might be happening? var cou ...

Displaying radio values in an Angular ng-repeat directive

I am new to Angular and facing difficulties in capturing the selected radio value when using ng-repeat. The documentation is a bit unclear on this matter. Any assistance or guidance would be highly appreciated. <div ng-repeat="item in ed"> <lab ...

Struggling to figure out how to make Bootstrap toast close or autohide properly

Looking to integrate Bootstrap 5 toasts into my ASP.NET web application, I have the code below. HTML <div class="row"> <div class="toast" id="companyUpdOK" name="compa ...

Exploring the realms of software testing with a blend of manual testing and automation using powerful tools such as

Although I am still relatively new to automation, I have already created a handful of tests using Webdriver and TestNG. These tests are data-driven, pulling parameters from Excel sheets. As someone who primarily works manually on test plans, teaching mysel ...

Tips for dynamically refreshing a collection of radio buttons using jQuery Mobile?

If I have a set of 3 radio buttons like this: <label for="a-1">A</label> <input type="radio" name="a" id="a-1" value="1" /> <label for="a-2">A</label> <input type="radio" name="a" id="a-2" value="2" /> <label for="a- ...

Utilizing JavaScript to implement an interactive :hover pseudo-class dynamic effect

After reviewing a question on adding a hover class to an element, I am now curious about how to do the opposite. I already have a main class for a button I am planning to create, where I will customize the background for each button using myButton.style.b ...

Using jasmine for mocking jQuery's getJSON callback function is a helpful technique in testing your

In my module, there is a load function that utilizes jQuery's getJSON function to fetch data. load(key,callback){ // validate inputs $.getJSON( this.data[key],'',function(d){ switch(key){ // perform actions on the data bas ...

What occurs when the update function returned by React.useState() is invoked?

Just recently, I delved into the world of React hooks and decided to implement a small feature using them. The feature enables hidden texts to be displayed when users click on hyperlinks. Although I managed to make the code work, it appears that there are ...

Prevent users from adding or removing any letters

Exploring the ACE Editor integration with AngularJS (utilizing UI-Ace). I have a question. Is it possible to limit the user's actions to: Only allow entering a predefined character (for example, ;) Prevent deletion of any characters except for the p ...

Utilizing Vue3 for Seamless State Persistence Upon Page Reloads

I recently switched to Vue3 and am exploring how to utilize vuex for state management. In my previous Vue2 setup, I would initialize the store upon app loading as shown below: // mains.js import VueRouter from "vue-router"; import Vuex from " ...

Using ajax to retrieve quotes and authors from online sources

I've recently started learning javascript and I'm currently working on the Random Quote Machine project on freecodecamp. The main goal is to show a random quote along with its author when the user clicks the "New Quote" button. However, I'm ...

What is the issue with undefined params in Next.js?

I have come across an issue with the function in app/api/hello/[slug]/route.ts When I try to log the output, it keeps showing as undefined. Why is this happening? The code snippet from app/api/hello/[slug]/route.ts is shown below: export async function G ...

I'm curious about the meaning of "!" in pseudo-code. I understand that it represents factorial, but I'm unsure of how to properly interpret it

Can someone explain the meaning of ! in pseudo-code to me? I understand that it represents factorial, but for some reason I am having trouble translating it. For example: I came across this code snippet: if (operation!= ’B’ OR operation != ’D’ O ...

How can we make the lines in the Highcharts force plot take up all the available width

Our design team has specifically requested that our stacked area charts fill 100% of the chart width, instead of stopping at the tick marks. To illustrate this, they have provided a mockup: View Mockup Currently, our chart does not extend to the full wid ...

Having trouble receiving a response when making a request to an API

I encountered an issue while trying to fetch an API. Initially, I received an error message stating that the message port was closed before a response was received. After removing all extensions, the error disappeared but now I am still unable to receive a ...

Determine the difference between dates using Angular 2's array filtering function

Here's a way to get the current time in seconds: let currentTimeInSeconds = new Date().getTime() / 1000; I have an array containing objects with an expirationDate property that returns expiration time in seconds. I can find the bills that have expir ...