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

Having success with Bash commands in the terminal, however encountering the error message 'curl: (1) Protocol ""https" not supported or disabled in libcurl' when utilizing it in a script

Encountered an issue where a curl request functions correctly in the command line but produces strange errors when executed within a script. Here is a snippet of the script: #we already got the $token #vars defining curl parameters dc="NA EU AU SEA JP ...

Despite being listed in the entry components, HelloComponent is not actually included in the NgModule

Check out my StackBlitz demo where I am experimenting with dynamically instantiating the HelloComponent using the ReflexiveInjector. The HelloComponent is added to the app modules entryComponents array. Despite this setup, I am still encountering the foll ...

Arranging and structuring Handlebars templates

In this particular example... http://example.com/1 ...I am experimenting with organizing a Handlebars template and its corresponding content in separate files, as opposed to having them all combined in the HTML file or JavaScript script, like in this con ...

What happens when Image Buttons are clicked in SAPUI5 and their onchange event is triggered

Is there a way to update the image on a button after it has been clicked? I want it to switch to a different image when activated. var offButton = new sap.ui.commons.Button({ id : "offIcon", icon : "img/off.png" , press :functio ...

Experiencing Challenges with JavaScript Implementation Within an HTML Document

Code: <!DOCTYPE html> <head> <script type="text/javascript" src="jquery-3.3.1.js"> </script> <script type="text/javascript"> $(function() { alert("Hello World"); }); </script> <meta charset ...

Encountering a Node.js issue when attempting to properly sanitize data before inserting it into MySQL

This is a snippet of code that I am using to insert data into a MySQL table. Before running the query, I escape the values like so: const mysql = require('mysql'); const R = require('ramda'); class Repository { constructor(connectio ...

JavaScript's square bracket notation is commonly used to access nested objects within an object

My goal is to accomplish the following: this.inputs[options.el.find('form').attr('class')] = {}; this.inputs[options.el.find('form').attr('class')][options.elements[x].selector] = false; Unfortunately, I'm fa ...

Generate a fresh Date/Time by combining individual Date and Time components

I have set up a form to gather dates from one input box and times from another. var appointment_date = new Date(); var appointment_start = new Date("Mon Apr 24 2017 20:00:00 GMT-0400 (EDT)"); var appointment_end = new Date("Mon Apr 24 2017 21:30:00 GMT- ...

Encountering an issue with the autocomplete feature in the jQuery library where it is stating "this.source is not a function."

Here's the code snippet I'm working with: $.ajax({ type: "GET", url: "https://url.com", dataType: "json", success: function (data) { $("#search").autocomplete({ source: data, select: function (even ...

Tips for integrating Material UI with useRef

There seems to be an issue with the code, but I haven't been able to pinpoint exactly what it is. My question is: How do you properly use useRef with Material UI? I am attempting to create a login page. The code was functioning fine with the original ...

Leveraging the Recyclability Aspect of a ReactJS Modal

Looking for a way to make a modal dynamic without duplicating too much code. Any suggestions on how to achieve this? I've managed to separate the state from the layout using render props. interface State { open: boolean; } interface InjectedMod ...

Error: Identifier Not Expected (Exploring Generators in ES6)

After delving into the information provided in the generators documentation on MDN, I devised a straightforward experiment: var nodes = { type: 'root', value: [ { type: 'char', value: 'a' }, { type: &ap ...

The application of document.body.style.backgroundColor is not compatible with an external CSS style sheet

Why does document.body.style.backgroundColor not work with an external CSS style sheet? I have the following CSS: body { background-color: red; } In my css style sheet, when I use JavaScript alert alert(document.body.style.backgroundColor);, it sh ...

Switching Angular fxLayout from row to column based on a conditional statementHere is an explanation of how to

Visit this link for more information Is there a way to set direction based on a specific value? <div if(value) fxLayout='row' else fxLayout='column'> ...

Creating a Gmail share button in AngularJS: A step-by-step guide

I created a messaging web application using AngularJS, and I successfully added functionality to share messages via email using the "mailto" link. However, this method only works if the user has an email client installed. Now, I am looking for a solution ...

What could be causing Highchart to return the error message "Typeerror: undefined variable byte"?

My current project involves creating a graph using highchart and updating values every second. I am also working on displaying data in Mb, Kb, and Gb format on the graph by developing a function to convert byte values. Here is a snippet of my code: // hi ...

Are there any alternative methods for clearing form fields following a successful thunk dispatch in React?

When implementing a Post API call in Thunk, I dispatch a boolean success key for successful requests and an error message for errors. Now the goal is to clear form data upon success and display the error message upon an error. To achieve this, I utilize ...

What methods are available to change one JSON format into another?

I am receiving JSON data from a Laravel API in the following format: [ { "id":48, "parentid":0, "title":"Item 1", "child_content":[ { "id":49, "parentid":48, "title":"Itema 1 ...

Sending data from a child component to a parent component in React

Trying to figure out how to pass the returned value of function appColor from the WeatherForecast component into a property, and then passing that property from WeatherForecast to the className of the app component. I'm new to React, so not sure how t ...

Seeking assistance in the development of a visual depiction of device orientation through JS

My goal is to visually represent the device orientation values alpha, beta, and gamma by creating a series of "bars" for each value. Currently, I have managed to display only the values in plain text using innerHTML. However, I envision these bars moving i ...