'Sorting array by date

Hello everyone. I want it to be sorted by date and rerender when clicking Recent. But I just couldn't. When I console.log I see the array as unsorted. and when I do console.log I get undefined. It feels like I'm missing something very simple but I couldn't figure it out. Where am i missing? Why console.log returns undefined ? Any help?



Solution 1:[1]

I have an idea for what you can do - arrange the date format in reverse (yyyy-mm-dd) then remove the - you will have a sortable number that you can use to sort the array.

Solution 2:[2]

1 convert to an array with JSON.parse() if the values are in JSON ... They not in your case pure array

2 Create a function and compare the dates using new Date()

  var arr = [{id: 1, date: Mar 12 2012 10:00:00 AM}, {id: 2, date: Mar 8 2012 
                08:00:00 AM}];
 
 sortByDate(arr) {
      arr.sort(function(a,b){
      return Number(new Date(a.readableDate)) - Number(newDate(b.readableDate));
      });

return arr;
}

Solution 3:[3]

Let's get to the error. First things first, the reason why you are getting undefined is you are having allFeeds object with feeds as an array. When you console.log(allFeeds.date) there is no key-value pair date in your allFeeds object, so it gives you undefined and when you do console.log(allFeeds.feeds.date) here you should use console.log(allFeeds.feeds[0].date) because allFeeds.feeds is an array.

To solve your problem, you can use the below solution.

a.sort((x,y)=>{return new Date(x.date.split("-").reverse().join("-")).getTime() - new Date(y.date.split("-").reverse().join("-")).getTime()})

We are doing this because the Date(dateString) recieves dateString in format yyyy-mm-dd and you are having date in dd-mm-yyyy which is not acceptable, also we are converting it to Date object because as a string dd-mm-yyyy or yyyy-mm-dd does not make much sense, after converting it to the Date object we can use its methods to use the data better.

Solution 4:[4]

Try this method

let arr = [
  {
    id: "1",
    title: "Amoos",
    details: [
      "Lorem ipsum dolor"
    ],
    img: "*",
    upvote: "3250",
    downvote: "2250",
    reviews: "5414",
    date: "2022-07-19"
  },
  { id: "2", date: "1990-12-01" },
  { id: "3", date: "2020-12-15" },
  { id: "4", date: "2007-12-12" }
];

function sortByDateFunc( d1, d2) {
  if (d1.date < d2.date) { return 1; }
  if (d1.date > d2.date) { return -1; }
  return 0;
}

const sortedData = arr.sort(sortByDateFunc);

console.log( sortedData );

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Steve
Solution 2 JonoJames
Solution 3 Manish Sencha
Solution 4 GMKHussain