Arranging array elements by both date and alphabetical order using Javascript

Is there a way to sort the data by both date and alphabet at the same time? Alphabetical order seems fine, but the date sorting isn't working correctly. Thank you for any solutions.

Data structure :

[{
    productId: 21,
    title: "Huawei P40 Lite ",
    brand: "Huawei",
    price: 120,
    discountPercentage: 10,
    color: "Black",
    createdDate: "2021-01-15T01:00:00+03:00",
  },
  {
    productId: 22,
    title: "Huawei P40 Lite",
    brand: "Huawei",
    price: 1026,
    discountPercentage: 0,
    color: "Green",
    createdDate: "2021-01-16T01:00:00+03:00",
  },
  {
    productId: 23,
    title: "Apple iPhone 11",
    brand: "Apple",
    price: 1220,
    discountPercentage: 11,
    color: "White",
    createdDate: "2021-01-17T01:00:00+03:00",
  },
 {
    productId: 24,
    title: "Apple iPhone 12",
    brand: "Apple",
    price: 1420,
    discountPercentage: 11,
    color: "White",
    createdDate: "2021-01-18T01:00:00+03:00",
  }],

My attempt can be found here:

jsfiddle.net/pazyqb01/

I have tried various methods to sort the dates but without success.

The sorted array should look like this:

 {
    productId: 24,
    title: "Apple iPhone 12",
    brand: "Apple",
    price: 1420,
    discountPercentage: 11,
    color: "White",
    createdDate: "2021-01-18T01:00:00+03:00",
  },
{
    productId: 23,
    title: "Apple iPhone 11",
    brand: "Apple",
    price: 1220,
    discountPercentage: 11,
    color: "White",
    createdDate: "2021-01-17T01:00:00+03:00",
  },
 {
    productId: 22,
    title: "Huawei P40 Lite",
    brand: "Huawei",
    price: 1026,
    discountPercentage: 0,
    color: "Green",
    createdDate: "2021-01-16T01:00:00+03:00",
  },
{
    productId: 21,
    title: "Huawei P40 Lite ",
    brand: "Huawei",
    price: 120,
    discountPercentage: 10,
    color: "Black",
    createdDate: "2021-01-15T01:00:00+03:00",
  },

Answer №1

Here's a simple approach:

Just stick to the criteria you have for sorting

const items = 
  [ { itemId: 1, name: 'Product A', category: 'Electronics', price: 350, discountPercentage: 15, color: 'Black', dateAdded: '2022-01-10T08:00:00+03:00' } 
  , { itemId: 2, name: 'Product B', category: 'Clothing', price: 50, discountPercentage: 5, color: 'Blue', dateAdded: '2022-02-13T14:00:00+03:00' } 
  , { itemId: 3, name: 'Product C', category: 'Home & Garden', price: 120, discountPercentage: 10, color: 'Green', dateAdded: '2022-03-20T09:00:00+03:00' } 
  , { itemId: 4, name: 'Product D', category: 'Electronics', price: 450, discountPercentage: 20, color: 'Silver', dateAdded: '2022-04-25T12:00:00+03:00' } 
  ] 

const customSort = (x,y) =>
  {
  let diff = new Date(y.dateAdded) - new Date(x.dateAdded)     // First criterion
  if (diff===0) diff = x.name.trim().localeCompare(y.name.trim()) // Second criterion

  // if(diff===0) diff = ... // Third
  // if(diff===0) diff = ... // Fourth....
  return diff
  }

console.log( items.sort(customSort))

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

Angular 7+: Trouble with displaying images from assets directory

Details regarding my Angular version: Angular CLI: 7.3.9 Node: 10.15.3 OS: win32 x64 Angular: 7.2.15 ... animations, common, compiler, compiler-cli, core, forms ... language-service, platform-browser, platform-browser-dynamic ... rout ...

How can I leverage Express, AngularJS, and Socket.io to facilitate broadcasting and receiving notifications?

A new notification system is in the works. To illustrate, User 1 is initiating a friend request to User 2. The technologies being utilized include express.js, angularjs, and socket.io. When User1 clicks the button, a request is sent. On User2's end, a ...

What is the method to provide function parameters without executing the function?

I'm searching for a solution to obtain a function that requires a parameter without actually invoking the function. Example of current malfunctioning code: const _validations = { userID: (req) => check('userID').isString().isUUID(&apo ...

Tips for accessing and modifying local JSON data in a Chrome Extension

I am working on an extension and need to access and modify a local JSON file within the extension's directory. How can I accomplish this task? ...

Load texture using ImageUtils with callback in Canvas Renderer

Currently, I am utilizing three.js revision 53. While attempting to load a texture in Canvas Renderer (specifically on Win7) and incorporating a callback for the onLoad event, the texture fails to display. Surprisingly enough, removing the callback functi ...

Could you lend a hand in figuring out the root cause of why this Express server is constantly serving up error

I am encountering a 404 error while running this test. I can't seem to identify the issue on my own and could really use another set of eyes to help me out. The test involves mocking a request to the Microsoft Graph API in order to remove a member fro ...

Manipulate a JSON object with JavaScript

Struggling to find a solution on my own. In my hidden field, I have some JSON data stored. To retrieve this data, I'm using the following syntax: $(document).ready(function() { var data = $("#result").text(); var j = JSON.parse(data); j.my_item.to ...

Unable to Update the Status Code

When it comes to setting the status code to 9999, I am utilizing the basic Response.StatusCode. In this case, the page is accessed via an AJAX call and the status code is checked at readyState = 4. On detecting 9999 as the status code, an alert pops up wit ...

Show information based on the user's role

I need to adjust my menu so that certain sections are only visible to specific users based on their roles. In my database, I have three roles: user, admin1, and admin2. For instance, how can I ensure that Category 2 is only visible to users with the ROLE_A ...

Struggling with incorporating a web link into a structured data table

I am currently working on a Django application that utilizes jQuery DataTables to display a list view of items. My goal is to include a hyperlink in the first element of the table, which represents the primary key for the model being displayed. This link s ...

Even after setting the handler to return false, Angular continues to submit the form

In the following scenario, I have encountered an issue: Here is the HTML template snippet: <form [action]='endpoint' method="post" target="my_iframe" #confirmForm (ngSubmit)="submitConfirmation()"> <button type="submit" (click)="conf ...

Ordering an Array of JavaScript Objects in a Custom Sequence (utilizing pre-existing methods)

Imagine we have an array of objects: ["c", "a", "b", "d"] Is there a way in ECMAScript or through a third-party JavaScript library to rearrange the objects in the first array to match the order specified by the second array, all within one line or functi ...

Struggling to loop through a child in Firebase real-time database?

I'm struggling to retrieve a nested child from my database with the following structure https://i.stack.imgur.com/ZDs38.png I am attempting to get the URI from the Gallery object. When I log in, I can see this in the console https://i.stack.imgur.c ...

Listener for 'timeupdate' event on video doesn't retain values

My html5 video event listener is designed to pause the video at a specific time while the user participates in a quiz. The first 'lesson' works fine, and the second video also appears to add the listener with the correct pause time. However, when ...

Issues with retrieving JSON data from Google Books API object

I've been working on retrieving data from the Google Books API and displaying the titles of the first 10 results on a web page. The site is successfully making the request, and I have a callback function that handles the results as shown below: funct ...

Is it possible to locate and eliminate the apostrophe along with the preceding letter?

My objective is to tidy up a character string by removing elements that are not essential for the user and SEO, specifically the (letter before the apostrophes) in this case. I am looking for a regex solution or explanation of how to achieve this in PHP, a ...

Having trouble connecting to the webserver? Make sure the web server is up and running, and that incoming HTTP requests are not being blocked by a firewall

While working on my Visual Studio 2013 Asp.Net web code using the Local IIS Web server Version 7 (Windows 7 x64) and Framework 4.0, I encountered an error message stating: "Unable to start debugging on the web server. Unable to connect to the webserver. V ...

Creating a seamless scrolling experience with a designated stopping point - here's how to achieve it!

I understand how to implement a scroll effect on an element with a specific class or ID. However, I am unsure of how to make the scrolling stop 20px above that element. I have seen examples using document.getElementById() to achieve this: function scr ...

What is the best way to compare two arrays of objects and then append a new key to the objects in the second array?

Consider the following arrays where you are tasked with comparing them and returning a filtered version of array two containing elements found in array one: const array1 = [ { name: "Jack", age: 54, title: "IT Engineer" }, { na ...

Is there a way to incorporate cell highlighting on IE?

I've implemented a method to highlight selected cells based on the suggestion from jointjs. It surrounds the cell with a 2-pixel red border, which works well in Chrome. However, I need the outline to work in IE as well. Unfortunately, when I reviewed ...