What is the best way to arrange an array of identical objects based on a specific sub property?

Here's an array of items to work with:

myArray = [
    {
      someDate: "2018-01-11T00:00:00",
      name: "John Smith",
      level: 5000
    },
    {
      someDate: "2017-12-18T00:00:00",
      name: "Jane Doe",
      level: 1000
    },
    {
      someDate: "2016-12-18T00:00:00",
      name: "Jack Black",
      level: 2500
    }
]

I'm attempting to arrange this array based on the date. Sorting arrays by simple properties isn't new to me:

Sorting JavaScript Object Array By Date

array.sort(function(a,b){
      return new Date(b.date) - new Date(a.date);
    });

However, I'm curious about sorting an array by its item properties. Any suggestions or tips would be appreciated.

EDIT: The date strings provided are indeed unusual and not in standard format due to a specific web service.

Answer №1

Your provided code is functioning perfectly as it is. To enhance it further, simply compare somedate instead of the current date, and then assign the sorted result back to the original array if needed.

myarray = myarray.sort(function(a,b){ 
      return new Date(b.somedate) - new Date(a.somedate); 
    }); 

Answer №2

If you follow the guidelines of ISO 8601 for your date format, it makes it easier to compare dates using a string comparer. This is because the values are organized in a descending order (year, month, day, hour, etc) and each unit has the same length.

var array = [{ somedate: "2018-01-11T00:00:00", name: "John Doe", level: 6000 }, { somedate: "2017-12-18T00:00:00", name: "Don Jhoe", level: 53 }, { somedate: "2016-12-18T00:00:00", name: "Jane Doe", level: 100 }, { somedate: "2018-10-18T00:00:00", name: "Dane Joe", level: 1 }];

array.sort(({ somedate: a }, { somedate: b }) => b.localeCompare(a)); // sort in descending order

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Employing the Map function in React leads to an error that is undefined

Upon simplifying my code, it seems that I am encountering an unresolved issue with the map function being used in different locations. I have noticed that code from examples running on platforms like Codepen does not work in my locally created react app p ...

What is the method to create a number using a textbox through javascript?

Whenever a number is entered into the main_textbox, a JavaScript function is called on the onblur event of the textbox using the following code: function generate_bale(){ var bale=document.getElementById("number_of_bale").value; var boxes = "< ...

What is the best way to eliminate the default hover effect using the MenuItem Mui class?

My goal is to eliminate the default gray hover over animation when using the MUI menu item class. I have attempted several methods, but none have been successful so far. Here are a couple of examples: <MenuItem divider sx={{'&:hover':{bac ...

Is the jqm flipswitch with the label on the left and the switch on the right?

My goal is to display multiple flipswitches on a mobile app page. This is the code I am using: <div class="ui-content"> <form> <fieldset> <div data-role="fieldcontain"> <label for="checkbox-based-flipswitch" ...

AngularJS: Issue with directive function not being executed

I created a directive in my code, but for some reason the function I provided to define the directive is not being called. It was working perfectly fine before, and now it just suddenly stopped without any clear explanation. Below is the code snippet of m ...

Is there a way to perform nested association counting in Sequelize?

Exploring ways to tally product reviews within nested associations using a specific query. const user = await User.findOne({ where: { id: req.query.user }, attributes: ["id", "name"], include: [ { model: Category, as: "interest ...

Send the contents of a `<ul>` element to the server using AJAX for form submission

Can someone assist me in submitting a serialized <ul> list through an AJAX post form request? I need help with this process. Below is my current code snippet. HTML: <form id="update_fruit_form" method="post" action="/update_fruits" accept-charse ...

File resolution issue with TypeScript

While I am aware that using TypeScript outFile is generally advised against, I currently have no choice but to utilize it until a more suitable solution like AMD can be implemented. It seems like there may be a "module splitting issue" in my project. In t ...

Swapping data between two HTML files and PHP

As I work on setting up a signup form for a MikroTik hotspot, I've encountered limitations with the device not supporting PHP. In order to pass the necessary variables from the device to an external PHP page where customer data will be saved and trial ...

Troubleshooting: Angular 6 Renderer2 Issue with Generating Dynamic DOM Elements for SELECT-Option

Currently, I am attempting to dynamically create a select option using Renderer2. Unfortunately, I am facing difficulties in creating the <Select></Select> element, but I can confirm that the <options> are being successfully created. Due ...

Testing the functionality of an Express.js application through unit testing

I'm currently working on adding unit tests for a module where I need to ensure that app.use is called with / and the appropriate handler this.express.static('www/html'), as well as verifying that app.listen is being called with the correct p ...

Troubleshooting problem with JSON decoding in PHP and json_encode

Encountering an issue when parsing JSON received from a PHP backend. In my PHP code, I have an array that I send using json_encode: $result[] = (object) array('src' => "{$mergedFile}", 'thumb_src' => "{$thumb_file}"); echo json_e ...

Using Vue.js to set both v-model and v-bind:value on one input element

I have a React component that has a form for submitting user information. The main issue I'm facing is setting a default value in the input field. When the page loads, I want the input field to display the user's existing email address by defaul ...

A vertical line in Javascript extending upward from the base of an element

Is there a way to create a design where an infinite vertical line extends from the bottom of a circle (or in my case, a rectangle) without using css :after or pseudo-elements? I would like the line to be its own element and not limited by the restriction ...

Struggling to find the right strategy for obtaining real-time data while implementing customized filters

After spending a week scratching my head and experimenting with different approaches, I'm hoping to find some help here... I am working on an application that needs to provide real-time data to the client. I initially considered using Server-Sent-Eve ...

Can you explain the concept of a "cURL" and guide me on how to use it effectively?

I'm currently working on setting up a Lyrebird application, but I only have a basic understanding of javascript and php. Despite my efforts to implement a cURL request from , I've encountered issues trying to get it to work in both javascript and ...

Combining two sets of data into one powerful tool: ngx-charts for Angular 2

After successfully creating a component chart using ngx-charts in angular 2 and pulling data from data.ts, I am now looking to reuse the same component to display a second chart with a different data set (data2.ts). Is this even possible? Can someone guide ...

Enhance your browsing experience with a JavaScript bookmarklet that allows you to easily search through

Struggling to develop a JS Bookmarklet that scans the source code of the current page for a specific code like "G1_Value_client." If found, I need it to trigger alert A; if not found, trigger alert B. Seeking assistance as I am facing some challenges with ...

Divide a JSON dataset into two distinct JSON files and incorporate them within the code

My JSON file structure is as follows: { "rID": "1", "rFI": "01", "rTN": "0011", "rAN": "11", "sID&quo ...

What is the proper way to retrieve the app object from a module in ExpressJS?

In my application, I am running an Express app by setting it up in the app.js file: var app = express(); Once the app is created, I can define variables like this: app.set('host', 'myhost') Now, within my project, I also have a sepa ...