Applying these sorting functions to my specific scenario

Hello everyone, I hope you can help me out with this issue. I have been struggling for hours trying to sort my array of objects in JavaScript based on a specific property, but I just can't seem to get it right.

I have referred to some of the top posts on Stack Overflow and tried a few different solutions, but none of them have worked for me. I want to sort my array of objects by the "horaInicial" property, which contains an ISO 8601 string.

Array(3)
0: Appointment
area: "S. Eter"
data: "2019-05-23T12:40:55.155+01:00"
description: "Sprint CS WEB"
horaFinal: "2019-05-21T11:40:59.028Z"
horaInicial: "2019-05-21T11:40:59.028Z"
id: 17
__proto__: Object
1: Appointment
area: "S. Confiança"
data: "2019-05-23T12:40:55.155+01:00"
description: "AR"
horaFinal: "2019-05-21T16:45:15.448+01:00"
horaInicial: "2019-05-21T16:00:15.448+01:00"
id: 18
__proto__: Object
2: Appointment
area: "djdndjsnsnsnzznj"
data: "2019-05-23T11:18:24.596+01:00"
description: "xbxnxnsnsjsjdjdkssjdjsjsk"
horaFinal: "2019-05-22T10:42:46.770Z"
horaInicial: "2019-05-22T11:41:46.769+01:00"
id: 23
__proto__: Object

Despite trying different sorting functions like the one below, the array remains unchanged:

    this.appointments.sort(function(a, b) {
        var textA = a.horaInicial.toUpperCase();
        var textB = b.horaInicial.toUpperCase();
        return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
     });

    console.log(this.appointments);

I am clearly missing something here. Can anyone point me in the right direction?

Answer №1

Make sure to properly parse the Date object in JavaScript to ensure accurate comparisons. Otherwise, you'll be comparing strings instead of actual dates.

If you want to use the sort() function in JavaScript and get the desired sorting output based on the horaInicial property, you should parse the dates within the sorting function. Here's how you can achieve that:

yourArray.sort(function(a,b){
  return new Date(b.horaInicial) - new Date(a.horaInicial);
});

By doing this, you'll get a descending array sorted by date. If you want to convert it to ascending order, you can simply use yourArray.reverse().

Here's an example to illustrate the process:

let yourArray = [
{
  area: "S. Eter",
  data: "2019-05-23T12:40:55.155+01:00",
  description: "Sprint CS WEB",
  horaFinal: "2019-05-21T11:40:59.028Z",
  horaInicial: "2019-05-21T11:40:59.028Z",
  id: 17
},
{
  area: "S. Confiança",
  data: "2019-05-23T12:40:55.155+01:00",
  description: "AR",
  horaFinal: "2019-05-21T16:45:15.448+01:00",
  horaInicial: "2019-05-21T16:00:15.448+01:00",
  id: 18
},
{
  area: "djdndjsnsnsnzznj",
  data: "2019-05-23T11:18:24.596+01:00",
  description: "xbxnxnsnsjsjdjdkssjdjsjsk",
  horaFinal: "2019-05-22T10:42:46.770Z",
  horaInicial: "2019-05-22T11:41:46.769+01:00",
  id: 23
}
];

// BEFORE SORTING THE ARRAY
document.write("Before:<br>");
yourArray.forEach((i)=> {
  document.write(new Date(i.horaInicial) + "<br>");
});

// SORT THE ARRAY
yourArray.sort(function(a,b){
  return new Date(b.horaInicial) - new Date(a.horaInicial);
});

// AFTER SORTING THE ARRAY
document.write("<br>After desc:<br>");
yourArray.forEach((i)=> {
  document.write(new Date(i.horaInicial) + "<br>");
});

// REVERSING ARRAY
yourArray.reverse();

// AFTER SORTING AND REVERSING ARRAY
document.write("<br>After asc:<br>");
yourArray.forEach((i)=> {
  document.write(new Date(i.horaInicial) + "<br>");
});

Answer №2

Why is it beneficial to convert timestamps into epoch format before sorting them? By converting timestamps into epoch, you can easily sort them using the resulting numbers.

1. To convert timestamps into epoch format, you can do the following -

 arr2 = arr.map(item => {
    item.horaInicialEpoch = new Date(item.horaInicial).getTime();
    return item; 
 })
  1. Sort the timestamps based on horaInicialEpoch

    arr2.sort((a,b) => a.horaInicialEpoch - b.horaInicialEpoch)

P.S Remember to only use string representations of time when displaying it for humans. For computational purposes, always utilize the seconds since epoch.

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

fetching data with Contentful and GatsbyJS

I am currently working on fetching data from Contentful using GraphQL within a Gatsby application, and here is my approach: type AllContentfulBlogs = { allContentfulBlogs: { nodes: Array<{ title?: string | null | undefined, ...

The textgeometry element is not appearing in the three.js scene

I've inserted a boxgeometry into the scene with the intention of adding text to indicate the side of the cube. However, I am encountering difficulties in incorporating textgeometry into the scene. This is my code: const loader = new FontLoader(); loa ...

Express in Node.js is designed in a way that error handling can only be done using the

Currently utilizing Node.js Express for developing HTTP REST APIs. The methods call a service that returns a Promise in the example below: function retrieveAllApps(request, response) { appService.getAllApps(request.query.$expand).then(function (apps) ...

Learn how to update a form dynamically using the Ajax.BeginForm feature

I am currently working on updating a form within my application using Ajax.BeginForm. The update process is functioning correctly, however, upon executing the function in the controller, it redirects to a view with the controller function name displayed. ...

"Implementing a call and waiting at intervals by utilizing the subscribe function in Angular 6

In my code, I have a method that is called every 10000 times. Now, I want to modify this so that the function getAllNotificationsActed0() is invoked every 10 seconds. If the data does not arrive within this interval, I do not want the function to be called ...

Having trouble getting Ajax to function properly with CodeIgniter

Here is the AJAX code snippet: $.ajax({ url: '<?php echo base_url(); ?>deleteRowUsingApiKey/index', //This is the current doc type: "POST", //dataType:'json', // add json datatype to get json data: {name ...

Tips for including and excluding personalized Chips from input

Just started learning React/typescript, any assistance would be greatly appreciated Custom Chip (CC.chip) is a specialized Chip UI component that can be utilized as demonstrated below. const [isOpen, setIsOpen] = useState(true); const onClose = Re ...

What is the best way to save inputted names as properties of an object and assign the corresponding input values as the values of those properties?

I am searching for a way to dynamically build an object where each property corresponds to the name of an input field and the value of that property is the input's value. Here is the HTML structure: <form> <fieldset> ...

How can I display only four decimal places by default within textboxes in HTML?

Looking for assistance with configuring textboxes in a cshtml file. The textboxes are bound to decimal fields in a view model and currently display nine zeros after the decimal point. I would like to limit the display to only four digits by default witho ...

Error with replacing regular expressions in IE11 for the variable $0

Having both a string and a message: str = "Test $0 $1 $2"; message = "Hi %2 Hello %2" ; The goal is to replace all occurrences of %2 with str in the message using RegExp, like so: message = message.replace(new RegExp("%2" , "g"), str); While this works ...

Sending an array of objects over socket io: A step-by-step guide

Recently, I've been struggling with an issue when trying to send an array of objects through socket io. This is my server-side code: var addEntity = function(ent) { entityBag.push(ent); }; var entityBag = []; addEntity(new Circle({ ...

`Angular2 Reactively-shaped Form Elements with BehaviorSubject`

As a newcomer to Angular, I am struggling with updating reactive forms after making asynchronous calls. My specific challenge involves having a reactive form linked to an object model. Whenever there is a change in the form, it triggers an HTTP request th ...

Ensuring a value is fully defined before passing it as a prop in a component

Is there a way to handle passing down state as a prop in a React component that is being fetched from an API using useEffect and axios? The state is initially set to "null", and I am encountering issues when trying to pass it down as a prop before it is ...

Registering a function for chart.js plugins that manipulates external data

Is there a way to pass external data to the chart.plugins.register function? I'm struggling because I can't access the necessary context: Chart.plugins.register( { beforeDraw: function (chart) { //implementation } }); I attempted using ...

Switching images dynamically using Flask and JavaScript

I'm currently working on Flask and encountering a perplexing issue. I'm attempting to update an image using JavaScript, but I am getting these errors from Flask: ... 12:05:34] "GET / HTTP/1.1" 200 - ... 12:05:38] "GET /img/pictur ...

Customize date filtering in KendoUI grid

I am trying to modify the date format in the filter of my kendo grid. For example, I would like to change 1/30/2015 to Jan 30, 2015 I have successfully changed the date format for Start Date field: "StartDate", title: " ...

The text "Hello ${name}" does not get substituted with the name parameter right away in the message string

I'm struggling to get the basic TypeScript feature to work properly. Everywhere I look on the Internet, it says that: var a = "Bob" var message = 'Hello ${a}' should result in a console.log(message) printing "Hello Bob". Howeve ...

Step-by-step guide to creating a custom wrapper in React that modifies the props for a component

Exploring React components for the first time and seeking assistance. I am interested in dynamically wrapping one component inside another and modifying its props. For instance, considering the following component: If we want to pass the key3 from a wrapp ...

Exploring File Read and Write Functionality in Angular 4

I want to develop an offline Task List in Angular 4. However, I am facing difficulty in finding a method to save data in a file on the client side using JavaScript or Angular. My current approach involves using browser's localStorage, but it is slow ...

Using Jquery to activate a vertical scrolling bar

Within my div, I have a tree view that extends beyond the size of the div, causing a vertical scroll bar to appear on the right side. When users click a button outside of the div, I want the page to scroll to a specific item within the div (which I know th ...