Sorting a React map function based on two fields

I am new to React and I am trying to sort an array by two different dates:

{folder.actions
  .sort((a,b) => {
    return a.date_actual - b.date_actual || a.date_sched - b.date_sched
   })
  .map(action => {
   ...

However, the code above is not working as expected. I need the sorting to be in descending order while also considering both "date_actual" and "date_sched" properties within the map function:

...
  <Col xs={4}>
    {action.date_actual ? 
      new Date(action.date_actual).toLocaleDateString() : 
      new Date(action.date_sched).toLocaleDateString()
     }
  </Col>
...
18/04/2021 (date_sched)
03/11/2020 (date_actual)
18/04/2021 (date_sched)
03/11/2020 (date_actual)
03/11/2020 (date_actual)
03/11/2020 (date_actual)
12/04/2021 (date_sched)
03/11/2020 (date_actual)
03/11/2020 (date_actual)

Thank you for your time and assistance!

Answer №1

If you want to sort based on two different date types simultaneously, you can utilize the || operator within your sorting logic. For instance, consider an array like this: (I'm using numbers for simplicity)

const yourArray = [
  { first_date: 0 },
  { second_date: 1 },
  { first_date: 3 },
  { second_date: 2 }
];

The desired outcome is as follows:

const yourArray = [
  { first_date: 0 },
  { second_date: 1 },
  { second_date: 2 },
  { first_date: 3 },
];

In JavaScript, you can specify to use either the first date or the second date if the first one doesn't exist.

yourArray
  .sort((a, b) => (a.first_date || a.second_date) - (b.first_date || b.second_date));

// const yourArray = [
//   { first_date: 0 },
//   { second_date: 1 },
//   { second_date: 2 },
//   { first_date: 3 },
// ];

Answer №2

Thank you for the prompt response,

Upon reviewing this code snippet:


{folder.actions
  .sort((a,b) => {
     return (a.date_actual || a.date_sched) - (b.date_actual || b.date_sched)
   })
  .map(action => {
...
return (
 ...
  <Col xs={4}>
   {action.date_actual ? 
     new Date(action.date_actual).toLocaleDateString() : 
     new Date(action.date_sched).toLocaleDateString()}
  </Col>

The displayed dates are as follows:

03/11/2020
18/04/2021
03/11/2020
18/04/2021
03/11/2020
03/11/2020
12/04/2021
03/11/2020
03/11/2020

In the input array, the dates are:

date_actual: "2020-11-03 17:30:30"
date_sched: null

There seems to be some inconsistency in the entries where date_actual is empty while date_sched is filled.

Answer №3

The sorting algorithm in your function will always prioritize the first condition since it consistently yields true results. To sort by both fields effectively, you must explicitly specify the conditions for each field:

For example: if (a.date1 > b.date2) && (a.date2 > b.date2) return 1 and continue this pattern...

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

Reorganizing MongoDB arrays with Prisma and NextJS

I'm dealing with data stored in MongoDB that looks like this: { items: [ { id: '6614005475802af9ae05b6b2', title: 'title', createdAt: '2024-04-08T14:33:56.734Z', }, { id: '6613f ...

What steps can I take to resolve the issue of text/data overflow within material-ui?

Having an issue with data overflow in my MaterialTable from material-ui when viewed on mobile devices. It displays fine on desktop, but the table data spills over on smaller screens. How can I resolve this problem? <MaterialTable className={clas ...

Incorporate communication between the front-end and backend

I encountered an error while attempting to import the getUser function in my backend code. The actual function is located in the frontend at ../utils/auth. How can I successfully import between front-end and backend? Or might there be another issue at pla ...

Utilizing Multiple Components on a Single Page in React.js

I'm currently setting up a React main page that renders two separate components - Header and Test. render() { return ( <Header /> <Test /> ); } The Header component contains static content, while the ...

Tips for successfully passing a function to a link component in React Router v6

I'm facing an issue with passing a function to a link component. I tried using state and useLocation, which work fine for regular variables, but useLocation returns null when attempting to pass down a function. const myFunction = someFunction(); < ...

The functionality of the React Material-UI menu anchor is disrupted when interacting with a react-window

In the project I am working on, I have encountered an issue with the Material-UI and react-window integration. Specifically, the material-ui menu component does not anchor properly when placed within a virtualized list created with react-window. Instead of ...

Leveraging the power of Framer Motion in combination with Typescript

While utilizing Framer Motion with TypeScript, I found myself pondering if there is a method to ensure that variants are typesafe for improved autocomplete and reduced mistakes. Additionally, I was exploring the custom prop for handling custom data and des ...

"Date validation issue with Formik and Material-UI's Datepicker component: min and max dates not

This particular issue has really been getting to me. I just can't seem to make the min and max date functionality work at all. Below is the snippet of code in question: <DatePickerField name={dob.name} label={dob.l ...

Reverting a React-Select child component back to its default values from the parent component

I am facing an issue with a parent component (Membership) that includes a child component (AboutYou). The parent component handles form submission using a button, which also triggers a reset action. The AboutYou child component contains a React-Select inp ...

React Hooks: Unable to re-enable input after it has been disabled

Attempting to manage the status of my points input whether it's enabled or disabled, I encountered an issue. Upon checking the checkbox, it correctly gets disabled. However, upon unchecking it, the input remains disabled. Initially, I attempted settin ...

Discovering instructions on locating Material UI component documentation

I'm having trouble locating proper documentation for MUI components. Whenever I attempt to replicate an example from the site, I struggle to customize it to fit my requirements. There are numerous props used in these examples that I can't seem to ...

Implementing a timed delay before assigning a class in the state

I am trying to implement a delay before applying for a new class. This is my current situation const [isDone, setIsDone] = useState<boolean>(false); Within a method, I have the following code snippet const myMethod = () => { .... .... se ...

Error: zone.filter is not a valid function and cannot be handled

Attempting to mark a location using Mapbox GL, I've installed react-map-gl and encountered the following error: Unhandled Rejection (TypeError): zone.filter is not a function. Can someone please assist me in resolving this issue? What am I doing incor ...

Customizing HTML element tags in MUI: Best practices

Using the most recent version of MUI (v5) and incorporating CssBaseline from @mui/materials. Typically, in CSS, I would set up my styles like this: body, html, #root { width: 100%; height: 100%; min-height: 100%; margin: 0; padding: 0; font-siz ...

Dealing with a failed login error in NextAuth.js

I've integrated NextAuth.js for authentication in my Next.js project. The login functionality is working smoothly, however, the page refreshes when incorrect credentials are entered without displaying any error message. I am looking to handle this err ...

Using multiple functions to organize nested variables within the useState hook

I'm stuck trying to figure out a part of my application, leading me to have some questions. I am working with a JSON string from an API as input for my project. This JSON string needs to generate multiple input fields on the page, which I then plan to ...

Reviewing and Implementing React and Material-UI Autocomplete for Selecting Multiple

Having trouble using Formik and MUI Autocomplete with multiple items. Specifically, when searching for "Pencil", it doesn't highlight the item. Also, you can select it twice by clicking on it. Desired outcome: Being able to select one or more items. ...

The issue of conflicting dependencies arises between [email protected] and @apollo/[email protected]

I am encountering an issue with @apollo while working on my react project, and I keep receiving the following error: npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: @apollo/<a href="/cdn-cgi/l/email-protect ...

I never receive back the funds I deposit into Formic

I am facing an issue with Formic where the value I store does not return to me as expected. The problem arises when the filter finds a specific value and logs it in line 57, then places the same value in Formic on line 58. However, when I log the Formic ...

Arrays in Vue Data

After creating an array and pushing data into it, the array turns into a proxy, preventing me from using JavaScript array functions on it. export default { name: 'Home', components: { PokeList, FilterType, SearchPokemon}, data() { r ...