Sort Array List by Boolean first, followed by Date in JavaScript/TypeScript

Introducing a new item dynamically to the list and organizing it by status followed by date. Here's the functional code:

I need the list to display items with false status in descending order of date first, then true status items sorted by date when adding a new item.

added item ={"Status":false,"Date":"2021-07-23T07:43:01.377Z","Title":"test6"}

List Order:-

var itemlist = [{
"Status":true,"Date":"2021-07-23T07:28:23.841Z","Title":"test5"},{
"Status":false,"Date":"2021-07-23T07:03:12.736Z","Title":"test4"},{
"Status":false,"Date":"2021-07-23T07:02:01.901Z","Title":"test3"},{
"Status":true,"Date":"2021-07-23T06:46:34.614Z","Title":"test2"},{
"Status":false,"Date":"2021-07-22T14:33:41.351Z","Title":"test1"},{
"Status":true,"Date":"2021-07-16T06:28:41.568Z","Title":"Test0"}];

Expected Outcome:-

var itemlist = [{
    "Status":false,"Date":"2021-07-23T07:43:01.377Z","Title":"test6"},{
    "Status":false,"Date":"2021-07-23T07:03:12.736Z","Title":"test4"},{
    "Status":false,"Date":"2021-07-23T07:02:01.901Z","Title":"test3"},{
    "Status":false,"Date":"2021-07-22T14:33:41.351Z","Title":"test1"},{
    "Status":true,"Date":"2021-07-23T07:28:23.841Z","Title":"test5"},{
    "Status":true,"Date":"2021-07-23T06:46:34.614Z","Title":"test2"},{
    "Status":true,"Date":"2021-07-16T06:28:41.568Z","Title":"Test0"}];

Actual Result:-

var itemlist = [{
    "Status":false,"Date":"2021-07-23T07:03:12.736Z","Title":"test4"},{
    "Status":false,"Date":"2021-07-23T07:02:01.901Z","Title":"test3"},{
    "Status":false,"Date":"2021-07-22T14:33:41.351Z","Title":"test1"},{
    "Status":false,"Date":"2021-07-23T07:43:01.377Z","Title":"test6"},{
    "Status":true,"Date":"2021-07-23T07:28:23.841Z","Title":"test5"},{
    "Status":true,"Date":"2021-07-23T06:46:34.614Z","Title":"test2"},{
    "Status":true,"Date":"2021-07-16T06:28:41.568Z","Title":"Test0"}];

Sorting Method Used:-

var res=itemlist.sort(
   (a, b) => (a.Status === b.Status ) ? 
      0 : (a.Status ? 1 : -1 || +new Date(b.Date)- +new Date(a.Date)));

Answer №1

To organize the list, you can:

  • Sort by Status in ascending order based on value,
  • Arrange Date in descending order as strings.

var itemlist = [{ Status: true, Date: "2021-07-23T07:28:23.841Z", Title: "test5" }, { Status: false, Date: "2021-07-23T07:03:12.736Z", Title: "test4" }, { Status: false, Date: "2021-07-23T07:02:01.901Z", Title: "test3" }, { Status: true, Date: "2021-07-23T06:46:34.614Z", Title: "test2" }, { Status: false, Date: "2021-07-22T14:33:41.351Z", Title: "test1" }, { Status: true, Date: "2021-07-16T06:28:41.568Z", Title: "Test0" }, { Status: false, Date: "2021-07-23T07:43 ...
itemlist.sort((a, b) => a.Status - b.Status || b.Date.localeCompare(a.Date));
console.log(itemlist);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

To implement sorting based on multiple criteria, you can utilize the logical OR operator within the sort callback function.

var itemList = [{
"Status":true,"Date":"2021-07-23T07:28:23.841Z","Title":"test5"},{
"Status":false,"Date":"2021-07-23T07:03:12.736Z","Title":"test4"},{
"Status":false,"Date":"2021-07-23T07:02:01.901Z","Title":"test3"},{
"Status":true,"Date":"2021-07-23T06:46:34.614Z","Title":"test2"},{
"Status":false,"Date":"2021-07-22T14:33:41.351Z","Title":"test1"},{
"Status":true,"Date":"2021-07-16T06:28:41.568Z","Title":"Test0"}];
itemList.sort((a,b) => a.Status - b.Status || new Date(b.Date) - new Date(a.Date))
console.log(itemList);

Answer №3

First and foremost, it is important to note that the elements in the Unordered list:- and Expected Result:- do not align in terms of quantity in your provided example data. When seeking assistance, accuracy in presenting the example data is crucial.

Resolution:

let compareFunction = (a, b) => {
    if (a.Status !== b.Status) {
        return a.Status ? 1 : -1;
    } else {
        return new Date(b.Date) < new Date(a.Date) ? -1 : 1;
    }
}

let result = itemList.sort(compareFunction);

Clarification:

In cases where the .Status does not match, priority is given to the element with false before proceeding to compare dates if the .Status matches.

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

With a single click, Clickaway is triggered not once, but twice

I am working on creating a filter component where I can pass filter options down to my child component. Each filter has a click event to open the filter for user selection, as well as a v-on-clickaway event that closes the options when the user clicks away ...

Expanding/Collapsing Indicator Stays in Place as Content Expands

I'm encountering a problem with my expand/collapse code. I want the p class="heading" tag in the HTML (which is responsible for toggling my expand/collapse box) to move down along with the expanding content. At the moment, the content expands and appe ...

Using JavaScript to extract the metadata of an image from a remote location

Is there a way to extract XMP metadata from a JPEG file using JavaScript? I came across a method for doing it in PHP (How can I read XMP data from a JPG with PHP?) which can be adapted for JavaScript using AJAX. However, the issue arises when trying to acc ...

Error encountered while using the getJSON code syntax

Is there an issue with this code snippet? I am receiving a syntax error on line 1: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Demo</title> </head> <body> <script src="http:/ ...

Issue with the Ajax auto-complete feature in Internet Explorer

I am facing an issue with my "ajax suggestion list" getting hidden behind the "select menu" located right below the text box that triggers the ajax function. This problem only occurs in IE 6.0, while it works fine in other browsers. I have already disabled ...

Intensive analysis of objects comparing their characteristics

Currently delving into the world of Javascript, I encountered a coding exercise involving a "deepEqual" function that I attempted to write but ultimately struggled with. Even after reviewing the solution, one particular part perplexed me - the for loop, ...

Implementing validation logic on button click using TypeScript

I'm struggling to get my validation to work for empty fields using the method below. Can anyone provide some guidance or suggestions? Thanks. Here is my template: <form [formGroup]="form" (ngSubmit)="onSubmit(form.value)" class="nobottommargin ad ...

What is the process for interacting with a Node.js Web API using an Angular JS API?

Seeking assistance with converting HTML into JADE format, encountering issues with {{record.name}} not functioning correctly. This is preventing the fetching and printing of values. Below are the complete file details: Directory view can be seen here. JS ...

When clicking on an HTML link pointing to a cloud, it does not open in the same frame but instead opens in a new window

I am currently working on an HTML5 application that features a screen divided into two parts. The left part of the screen contains a few links, and upon clicking one of these links, the resulting content should open in the right side frame within the same ...

Utilizing React Hooks as a shared component in TypeScript: a comprehensive guide

I have a SnackBar.ts file as shown below import { useSnackbar } from 'notistack'; const SnackBar = (message:string, isError?:boolean) => { const { enqueueSnackbar } = useSnackbar(); return enqueueSnackbar(message, { anchorOrigin: { ...

Is there a way to confirm the presence of multiple attributes in a JSON format using JavaScript?

Currently, I am developing a module that processes multiple complex JSON files and requires a method to notify users if certain elements are missing. Although the current approach works, I can't shake the feeling that there must be a more efficient a ...

Tips for modifying CSS when a user scrolls beyond a specific div

Currently, I am working on implementing a scroll function that dynamically moves elements based on the user's scrolling behavior. The code I have written works to some extent and successfully moves the elements. However, my goal is to create a list o ...

Initialize a jQuery UI resizable element by selecting a specific element that has been dynamically added to the DOM

Is there a way to start a jquery ui resizable instance using a selector added to the DOM by jquery itself? Here is a snippet of the script I am currently working with: HTML: <div class='lyr'></div> jQuery: // Add class $('lyr ...

Guide on implementing tail.select in a VueJS project

As a newcomer to VueJS, I am facing issues with using the tail.select plugin in my VueJS project. Even though I have imported the plugin in my main.js file using import 'tail.select' When I try to call tail.select(".select") in the mounted hook ...

The submit button fails to function properly in the presence of multiple fields

Encountering an issue where the Submit button becomes unresponsive when multiple addresses are generated. To resolve this, I attempted to use JavaScript. @foreach ($userDetails as $addr) <div class="order_container"> <input type="hid ...

Newest preact and typescript packages causing issues with type validation

Despite my efforts to integrate preact with TypeScript, I have encountered a problem where incorrect types can be passed without any error being raised. I am in the process of transitioning our codebase from plain JavaScript to preact with type scripting. ...

Efficiently assign multiple attributes using a single d3 function

Hey everyone! I'm currently working with SVG lines and have come across an example object that looks like this: { _id: 5, coordinates:{ x1: 100, y1: 100, x2: 500, y2: 500, } Now, imagine I have an array of these obje ...

reinstate dummy of external class method in ts-jest

Problem I am encountering an issue while trying to mock a function that is imported from another class and called within the main class. Although I can successfully mock the function and return the specified values, I am unable to revert the mocked functi ...

Tips for retaining spaces in a multiline string when setting a helm value using cdktf

Currently, I am utilizing CDKTF to facilitate the deployment of the datadog helm chart into a kubernetes cluster. My objective is to assign a specific value to confd, however, the issue arises when the spaces in my typescript multiline string do not mainta ...

Why is it necessary to redefine the interface and its class in Typescript after initially defining the interface with implements?

interface Filter { rowAddRow: (treeData:Tree[],id:string,filterType:FilterType) =>Tree[] } class FilterAction implements Filter { // I must redeclare here to ensure the correct type for id rowAddRow(treeData:Tree[], id, filterType):Tree[] { ...