Home > other >  Sorting array by date
Sorting array by date

Time:04-10

export const allFeed = {  feeds: [
{
  id: "1",
  title:
    "Shang- Chi Stays On Record pace With Nearly $35.8 Million In Second Weekend",
  details: [
    "Lorem ipsum dolor, sit amet consectetur adipisicing elit. Esse minima ex rem quis similique eum ratione quaerat, voluptas molestias ut repudiandae delectus voluptates. Eius esse at tenetur ab accusamus excepturi?",
  ],
  img: "*",
  upvote: "3250",
  downvote: "2250",
  reviews: "5414",
  date: "19-07-2022",
},
{
  id: "2",
  title:
    "Daniel Craig: post your question for actor ahead of his final Bond film",
  details: [
    "Lorem ipsum dolor, sit amet consectetur adipisicing elit. Esse minima ex rem quis similique eum ratione quaerat, voluptas molestias ut repudiandae delectus voluptates. Eius esse at tenetur ab accusamus excepturi?",
  ],
  img: "*",
  upvote: "2050",
  downvote: "1350",
  reviews: "2253",
  date: "18-07-2019",
},.................



    export default function Feed({ feeds }) {
  const [allFeeds, setAllFeeds] = useState([]);

  const sortArray = (date) => {
    const allDates = {
      date: allFeeds.date,
    };
    const sortProp = allDates[date];
    const sorted = [...allFeeds].sort((a, b) => b[sortProp] - a[sortProp]);
    console.log(sorted);
    setAllFeeds(sorted);
  };

  useEffect(() => {
    setAllFeeds(feeds);
  }, []);

  return (
    <div className="feed">
      <div className="up-left">
        <div>
          <h3>Popular</h3>
        </div>
        <div>
          <h3 onClick={sortArray}>Recents</h3>
        </div>
      </div>
      {allFeeds.map((feed) => (
        <div key={feed.id} className="card">
          <div>
            <p className="feed-title">{feed.title.substring(0, 200)}...</p>
            <div className="card-element">
              <p className="votes">
               .........................

sort

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(allFeeds.date) or (allFeeds.feeds.date) 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?

CodePudding user response:

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.

CodePudding user response:

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;
}

CodePudding user response:

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.

CodePudding user response:

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 );

  • Related