Arranging an array based on various conditions and criteria

I am struggling to incorporate sorting and ordering into an array.

The obstacle I am encountering involves having 5 criteria for sorting, which are:

  1. due_date === 1000
  2. status && is_approved(boolean)
  3. is_overdue(boolean checking with date-fns using the due_date)
  4. due_date (either null, or number)
  5. is_approved

My goal is to create a sorting function that arranges the above criteria in the following order (from highest to lowest):

  1. due_date === 1000

  2. is_overdue (I am utilizing isAfter of date-fns which returns a boolean)

  3. status === 'DONE' && !is_approved

  4. due_date starting from lowest to highest (ignore the null values)

  5. is_approved === true

  6. any other remaining object

I was considering possibly using the .map method and adding a ranking value for each object by assessing the criteria, but there must be a way to accomplish this in a single iteration with the .sort method. I have already looked at other StackOverflow threads, yet most of their data is relatively straightforward such as age, name etc.

[
    {
      due_date: 150000,
      is_approved: false,
      is_overdue: true,
      status: 'TODO',
    },
    {
      due_date: 200000,
      is_approved: true,
      is_overdue: false,
      status: 'DONE',
    },
    {
      due_date: 150000,
      is_approved: false,
      is_overdue: false,
      status: 'IN PROGRESS',
    },
    {
      due_date: 1000,
      is_approved: false,
      is_overdue: true,
      status: 'TODO',
    },
    {
      due_date: 200000,
      is_approved: true,
      is_overdue: false,
      status: 'DONE',
    },
    {
      due_date: null,
      is_approved: false,
      is_overdue: true,
      status: 'TODO',
    },
  ]

Which I want to convert to;

[
    {
      due_date: 1000, // By due_date 1000 - highest ranking
      is_approved: false,
      is_overdue: true,
      status: 'TODO',
    },
    {
      due_date: 150000,
      is_approved: false,
      is_overdue: true, // Is overdue - second highest
      status: 'TODO',
    },
    {
      due_date: null,
      is_approved: false,
      is_overdue: true, // Is overdue - second highest
      status: 'TODO',
    },
    {
      due_date: 200000,
      is_approved: false, // Is not yet approved
      is_overdue: false,
      status: 'DONE', // and Is DONE
    },
    {
      due_date: 150000,
      is_approved: false,
      is_overdue: false,
      status: 'IN PROGRESS',
    },
    {
      due_date: 200000, // Lowest ranked
      is_approved: true, // Is APPROVED approved
      is_overdue: false,
      status: 'DONE', // and is DONE
    },
  ]

Answer №1

When sorting, remember to reverse the deltas of boolean values. This means that if you want to prioritize true values at the top, use b - a.

Take a look at the desired properties and their corresponding values:

  • due_date === 1000 (descending)
  • is_overdue (descending)
  • is_approved (ascending)
  • status === 'DONE' + !is_approved (sum ascending)
  • due_date === null (ascending)
  • due_date (descending)

const
    data = [{ due_date: 150000, is_approved: false, is_overdue: true, status: 'TODO' }, { due_date: 200000, is_approved: true, is_overdue: false, status: 'DONE' }, { due_date: 150000, is_approved: false, is_overdue: false, status: 'IN PROGRESS' }, { due_date: 1000, is_approved: false, is_overdue: true, status: 'TODO' }, { due_date: 200000, is_approved: false, is_overdue: false, status: 'DONE' }, { due_date: null, is_approved: false, is_overdue: true, status: 'TODO' }];

data.sort((a, b) =>
    (b.due_date === 1000) - (a.due_date === 1000) ||
    b.is_overdue - a.is_overdue ||
    a.is_approved - b.is_approved ||
    (a.status === 'DONE' + !a.is_approved) - (b.status === 'DONE' + !b.is_approved) ||
    (a.due_date === null) - (b.due_date === null) ||
    b.due_date - a.due_date 
);

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

Answer №2

To effectively organize the data, a sorting function must be defined

The initial requirements have been met, leaving the completion of the task in your hands

A bit of restructuring may be necessary, but the concept is clear

const data = [
    {
      due_date: 150000,
      is_approved: false,
      is_overdue: true,
      status: 'TODO',
    },
    {
      due_date: 200000,
      is_approved: true,
      is_overdue: false,
      status: 'DONE',
    },
    {
      due_date: 150000,
      is_approved: false,
      is_overdue: false,
      status: 'IN PROGRESS',
    },
    {
      due_date: 1000,
      is_approved: false,
      is_overdue: true,
      status: 'TODO',
    },
    {
      due_date: 200000,
      is_approved: true,
      is_overdue: false,
      status: 'DONE',
    },
    {
      due_date: null,
      is_approved: false,
      is_overdue: true,
      status: 'TODO',
    },
  ]
  
  
 const sortingFn = (a, b) => {
  if(a.due_date === 1000){
    return -1
  }
  if(b.due_date === 1000){
    return 1
  }
  
  if(a.is_overdue){
    return -1
  }
 
   if(b.is_overdue){
    return 1
  }
  //additional sorting conditions go here
 }
 
 data.sort(sortingFn)
 console.log(data)

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

Adding data to each span and div using JavaScript is a simple task that can be achieved easily

What is the best way to add information to each span and div element using JavaScript? $(document).on("click",".selection-state",function(){ stateid = $(this).attr("rel"); $("#my_tooltip").html(data); } e ...

Managing errors with async/await in an Angular HttpClient function

I have been experimenting with an async/await pattern to manage a complex scenario that could potentially result in "callback hell" if approached differently. Below is a simplified version of the code. The actual implementation involves approximately 5 co ...

Having trouble sharing content from my React next.js website on social media due to issues with open graph meta tags

I'm currently facing an issue with my Next.js application when trying to share content on Facebook and Twitter. I've made sure to include the necessary open graph meta tags in the document's head section and I'm using React Helmet to dy ...

Reading values from a properties file using HTML

Here's a snippet of my HTML code: First name: <input type = "text" > Last name: <input type = "text"> Instead of manually inputting the field values (First name, Last name) in the HTML, I am interested in reading them ...

React application experiencing issues with MQTT and Mosquitto broker connectivity

Upon installing the Mosquitto broker, I successfully tested it in my command prompt. However, when I attempted to establish a connection with my React application, I encountered the error message: "WebSocket connection to 'ws://localhost:1883/' f ...

The then() function in Node.js is triggered before the promise is fully resolved

I'm struggling to get my Promise function working as intended. Here's what I need to accomplish: I am receiving file names from stdout, splitting them into lines, and then copying them. Once the copy operation is complete, I want to initiate oth ...

Parsing dates arriving from a Restful Service in JavaScript

When I make a Restful call, the JSON response contains dates in a strange format like this: /Date(-62135568000000)/ What is the simplest way to convert it to a normal date format like (January 10, 2016)? I have read some articles that suggest using rege ...

PHP glob() function and its usage with arrays

It seems like I'm missing something, as I can't seem to find a solution to this problem. My goal is to modify the format of the array returned by the glob function. This is the current state of my code: $my_files = glob('*.php'); Th ...

Different ways to display array elements in List Item Text

Recently I started working with React and I'm using ListItemText to display values on the screen. My query is how can I utilize ListItemText to display all the elements of an array in a list. Below is the code snippet where Kpi_Before represents the ...

Struggling to pass along the URL value from a promise to various modules within Express is proving to be quite a challenge for me

I've been working on an app using ngrok, following a guide from Phil on setting up ngrok with nodemon. You can find the link to the post here. I need to have access to the URL received from the promise in the bin folder throughout the app server so t ...

Modify the color of the panel header when the button is clicked

I am trying to modify the background color of my panel header using a button that changes the color scheme of my site. The button currently functions on AFO. Below is the stylesheet for the button: .AFO { background-color: #fff;} .AFO h1 { color: #00159d; ...

Effortless code formatting with VS Code for TypeScript and JavaScript

Does anyone know of any extensions or JSON settings that can help me format my code like this: if(true) { } else { } Instead of like this: if(true){ } else { } ...

What is the best way to display JSON data in a Listview control?

What is the best way to display JSON data in a list format? Currently, I am able to retrieve JSON data and display it in an alert dialog. The JSON data looks like this: [{"_id":"5449f20d88da65bb79a006e1","name":"name3","phone":"888888","service":"service ...

Tips for displaying a jQuery error message when a key is pressed

I am working with a textarea that has a word count limit of 500. I need to display an error message below the textarea if the word count exceeds 500. I have successfully calculated the word count, but I am unsure how to display the error message and preve ...

Incorporating JSON into a ColdFusion program

I have a website that showcases different views for registered and non-registered users. I am currently redesigning the product navigation to make it easier to manage by using JSON format. My website is built on Mura CMS with ColdFusion. Although what I ...

What is the best way to utilize the request information within the app directory, similar to how it is done with the getServerSide

I am looking for a way to access the request data in my component. I have looked through the documentation but haven't been able to find a solution yet. If it's not possible to see the request data directly, are there any alternative methods I c ...

Boost Page Speed with Angular

Currently, I am working on a project using Angular and encountered an issue with testing the page speed on GTmetrix. Despite generating the build with the command ng build --prod--aot, the file size is 1.9mb, leading to a low speed in GTmetrix's analy ...

Make the element switch from hidden to visible when hovering over it using CSS

I had a challenge to only show some rating text on my website when I hovered over it. Being new to coding with CSS and JavaScript, I was experimenting with overriding styles using the Stylebot extension in Chrome. I encountered an issue while trying to mo ...

What is the optimal location for storing JSON data while dynamically loading via AJAX?

Let's imagine a scenario where there is an HTML page hosting a dynamic modal box. Clicking on different links within the page triggers the modal to open, each showing different content based on the clicked link. The dialog contents are fetched using A ...

Is there a straightforward method for tallying numbers in mongoose?

Here's the code I've written: Company.count({}, function(err, company) { Checkpoint.count({}, function(err, checkpoint) { Guard.count({}, function(err, guard) { Device.count({}, function(er ...