Sort Messages By Date Created

While using Vue, I encountered a general JavaScript question. I am fetching cat messages from an API for a chat interface. The initial call returns an array of objects where each object represents a chat message:

data: [
  {id: 1, created_at: "2022-05-20T15:12:40.000000Z", updated_at: "2022-05-20T17:18:03.000000Z",…},
  {id: 2, created_at: "2022-05-20T15:12:41.000000Z", updated_at: "2022-05-20T17:18:04.000000Z",…},
  {id: 3, created_at: "2022-05-20T15:12:41.000000Z", updated_at: "2022-05-20T17:18:04.000000Z",…},
  {id: 4, created_at: "2022-05-20T15:12:41.000000Z", updated_at: "2022-05-20T17:18:04.000000Z",…}
]

Initially, I tried to format the messages based on their dates in the chat window. Here's the code snippet I used:

This is a computed property in Vue

    const formattedChats = computed(() => {
      let dateFormattedMessages = messages.value.map(message => {
        return {...message, updated_at: new Date(message.updated_at).toDateString(), created_at: new Date(message.created_at).toDateString()}
      })
      return dateFormattedMessages.reduce((total, currentValue) => {
        total[currentValue.updated_at] = total[currentValue.updated_at] || [];
        total[currentValue.updated_at].push(currentValue);
        return total;
      }, Object.create(null));
    })

The above snippet first converts the updated_at and created_at properties of each chat object into date strings, and then groups the array by the updated_at property. The resulting structure looks like this:

formattedChats = {
  Fri Jun 24 2022: [{...}, {...}],
  Fri May 20 2022: [{...}, {...}],
  Mon Jun 27 2022: [{...}, {...}],
  Sat May 21 2022: [{...}, {...}],
  Tue Jun 28 2022: [{...}, {...}]
}

The issue I'm facing is that the dates are not sorted in any order. This makes it difficult to render the chats in the UI as they won't be displayed chronologically. Here's how the UI should ideally appear: https://i.sstatic.net/iq0LL.png

Answer №1

To maintain a sorted order, consider using arrays or a map. One approach is to utilize an array of arrays. Begin by sorting the data based on dates (using updated_at, assumed to be of Date type in the data array). Subsequently, iterate through the sorted array. Refer to the code snippet below for implementation.

const data = [{
    id: 1,
    updated_at: new Date("2022-05-21T15:12:40.000000Z"),
    created_at: "2022-05-20T17:18:03.000000Z"
  },
  {
    id: 2,
    updated_at: new Date("2022-05-20T15:12:41.000000Z"),
    created_at: "2022-05-20T17:18:04.000000Z"
  },
  {
    id: 3,
    updated_at: new Date("2022-05-23T15:12:41.000000Z"),
    created_at: "2022-05-20T17:18:04.000000Z"
  },
  {
    id: 4,
    updated_at: new Date("2022-05-21T15:12:41.000000Z"),
    created_at: "2022-05-20T17:18:04.000000Z"
  },
]

const sortedData = data.sort(
  (a, b) => Number(a.updated_at) - Number(b.updated_at),
);

let currentDay = sortedData[0].updated_at;

const stillCurrentDay = (dayOfMessage) => {
  return dayOfMessage.getFullYear() === currentDay.getFullYear() &&
    dayOfMessage.getMonth() === currentDay.getMonth() &&
    dayOfMessage.getDate() === currentDay.getDate()
}

let dayMessageArray = [];
const fullMessageArray = [];

const createMessagesArray = (messages) => {
  const newDay = {};
  newDay[currentDay.toISOString().split('T')[0]] = messages;
  fullMessageArray.push(newDay);
}

sortedData.forEach(message => {
  if (!stillCurrentDay(message.updated_at)) {
    createMessagesArray(dayMessageArray);
    currentDay = message.updated_at;
    dayMessageArray = [];
  }

  dayMessageArray.push(message);
});

createMessagesArray(dayMessageArray);

console.log(fullMessageArray);

Feel free to reach out if you need further assistance. There might be simpler solutions available as well, so do share your insights.

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

Run a Python function in Django without any feedback

Currently, I am utilizing Django for a project and I find myself in a situation where I need to carry out certain functions based on user input. If the action requires displaying new values, I know how to handle that. However, when I simply need to execute ...

Is there a way to connect a Button to a different page in VUE.JS?

I currently have a button that needs to be linked to another page. This is the code I am working with at the moment. How can we write this login functionality in vue.js? It should direct users to the page "/shop/customer/login" <div class="space-x ...

The Materialize CSS tabs are aligning vertically below each other, but functioning correctly upon refreshing the page

When using materialize css tabs, all the divs load one below the other on the initial page load. If I refresh the page, it starts behaving properly. <div class="row"> <div class="col s12"> <ul class="tabs"> <li class="tab col s ...

Is it possible to update the anchor to direct to the data-url attribute of the page?

In order to make my site's navigation more user-friendly, I want the page to scroll to a specific div when an a tag is clicked. This div should have a data-url attribute that matches the href of the clicked a tag. Essentially, the a tag should not nav ...

Is it a problem with Cucumber Js callbacks or a feature issue?

I would like to create a scenario similar to this: Scenario: initialize new Singleton When an unmatched identity is received for the first time Then create a new tin record And establish a new bronze record And generate a new gold record This s ...

Tips for combining arrays into one array in php

Consider the following two arrays: First Array: Array ( [0] => EXTRA [1] => CURRICULAR ) Second Array: Array ( [0] => ACTIVITIES [1] => 50 [2] => 35 [3] => THIRTY [4] => FIVE [5] => PASS ) Desired Output: Array ...

Error: The property 'case sensitive routing' cannot be accessed because it is undefined

Task at hand: Running ExpressJS port using Node.js, nodemon, and lib. Operating System: Windows 10 Home x64 Node.JS Version: Lts The Challenge: Getting the ExpressJS port to run successfully. Current Issue: Encountering an internal file error, potentiall ...

update url to redirect hashbang with history.js

Upon further investigation, I have observed that history.js has the ability to automatically transform http://www.site.com/some/path#/other/path into http://www.site.com/other/path when used with a html5 enabled browser. While this feature is useful, ...

Retrieve data from external URL using API

I am encountering a captchas page when attempting to retrieve JSON data from a URL through my API. Even though I am trying to access an array of JSON data containing openPrice, highPrice, price, and lowPrice, all I seem to get is a captcha form instead of ...

Discovering ways to enhance time multiplication with JavaScript

My MVC model provides me with a timespan like this: timeTaken = "00:01:00"; Along with a multiplier value of multiply = "3"; The end result should be 00:03:00 What would be the most efficient way to calculate this time? I'm not well-versed in ...

What reasons might lead an object to be passed to a view as the exact term 'object' in Express.js?

Using nodejs, express, and ejs. I have a variable called 'result' which is properly defined. When I use console.log(result) within the router.get function on my index page, it outputs a correctly structured array of objects. After that, I rende ...

What is the best way to navigate between different areas of an image using html and javascript?

I am currently in the process of learning how to develop mobile applications, and I am still in the early stages. Although this question is not directly related to mobile development, it pertains more to html/css/js. My goal is to create a simple game wh ...

The button's status changes to disabled until I click outside the input field in Angular

I am currently facing an issue with a form (heat index calculator) that requires 2 inputs - a dropdown and a button. The button is disabled when there are no inputs or if the inputs are invalid. Everything works correctly, except for the fact that even whe ...

"Obtaining a three.js sprite within a Verold script - the ultimate guide

Greetings fellow users of stack overflow! I've recently been experimenting with the world editor known as verold, based on three.js. The features it offers are quite impressive, but I've encountered an issue with the scripting aspect. My curren ...

What is the best way to switch the CSS style of a button that has been mapped

I'm currently working on toggling the CSS class for an individual button that is created from a mapped array. Although my code is functional, it toggles the CSS class for all buttons in the mapped array instead of just the one selected. ...

Storing objects in localStorage using VueJS

Is there a way to send all theme configuration settings as objects instead of recording them one by one? Can you provide an example if possible? Also, how do I set it on the store? I'm new to storage management so kindly provide guidance accordingly. ...

Retrieve data from a JSON object and assign it to a variable in JavaScript

I'm currently working on implementing AJAX to send and receive data in Django. My model consists of three fields: id, parent, and text. However, when attempting to post the information back to Django, I encounter an error due to additional fields pre ...

"Initiate an Ajax call in Full Calendar before an event is displayed on the calendar

I need guidance on how to integrate ajax calls with the Full Calendar documentation. Specifically, I want to make an ajax call to a WordPress database before each event is rendered on the calendar. The response from the call will determine the color of the ...

Find the current elapsed time using Wavesurfer in real time

I am currently utilizing the waveSurfer library created by katspaugh for playing audio files. In order to display 'elapsed time / total time', I have written code in the following manner: waveSurfer.on('play', function() { $scope.g ...

Unable to maintain sequential IDs for textboxes using Javascript or JQuery

I am encountering a problem involving the addition and deletion of multiple text boxes using buttons. The issue lies in maintaining sequential IDs for each textbox. Below is an explanation of my code: <div class="form-group" id="intro-box"> < ...