0

I have displayed data of an API in a table form and I am trying to sort the data date wise but I am not getting it correct. If anyone can help me with it, it will be helpful.

const groupedByDate = res.data.reduce((meals, meal) => {
          if (meal.date in meals) {
            meals[meal.date].push(meal);
          } else {
            meals[meal.date] = [meal];
          }
          return meals;
        }, {});
        const sortedOnDate = Object.values(groupedByDate).sort((arr1, arr2) => {
          if (arr1[0].date < arr2[0].date) {
            return -1;
          } else if (arr1[0].date > arr2[0].date) {
            return 1;
          }
          return 0;
        });
        setData(sortedOnDate);
      });

I have also added a code sandbox of what I have tried

DEMO

It will be very helpful if u can edit the sandbox and provide a working example

1
  • that have nothing to do with the sorting. anyway i have removed the errror Commented Dec 30, 2021 at 7:52

1 Answer 1

1

It is sorted that way because your date format is DD-MM-YYYY You can sort date if it's in YYY-MM-DD format.

It's a bit hacky but it works in your current codebase.

const sortedOnDate = Object.values(groupedByDate).sort((arr1, arr2) => {

      // Convert DD-MM-YYYY into YYYY-MM-DD
      const ymdDate1 = arr1[0].date.split("-").reverse().join("-");
      const ymdDate2 = arr2[0].date.split("-").reverse().join("-");
      if (ymdDate1 < ymdDate2) {
        return -1;
      } else if (ymdDate1 > ymdDate2) {
        return 1;
      }
      return 0;
    });
    setData(sortedOnDate);
Sign up to request clarification or add additional context in comments.

2 Comments

ur code is working but the date is sorted in accecding order im looking to sort it in decensing order
you can swap return -1 and return 1 to get descending order.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.