You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何按对象日期对数组排序?附API数据示例

How to Sort an Array by Date Fields in React

Hey there! Let's figure out how to sort your array of developer entries by their date fields in React. Looking at your sample data, we've got two different date formats to handle: Today, 5:32 PM (relative time) and 10 April 2018 (absolute date). The key here is first converting these strings into comparable Date objects, then using JavaScript's array sort() method to order them.

Step 1: Create a Date Parsing Function

First, we need a helper function to turn those date strings into valid Date instances. This will handle both relative ("Today") and absolute date formats:

const parseDateString = (dateStr) => {
  // Handle "Today, HH:MM PM/AM" format
  if (dateStr.startsWith('Today')) {
    const today = new Date();
    const timePart = dateStr.split(', ')[1];
    const [time, period] = timePart.split(' ');
    let [hours, minutes] = time.split(':').map(Number);
    
    // Convert 12-hour clock to 24-hour for accurate Date creation
    if (period === 'PM' && hours !== 12) hours += 12;
    if (period === 'AM' && hours === 12) hours = 0;
    
    today.setHours(hours, minutes, 0, 0);
    return today;
  }
  
  // Handle "DD Month YYYY" format (e.g., "10 April 2018")
  return new Date(dateStr);
};

Step 2: Build Sort Functions

Next, let's create reusable sort functions for ascending (oldest first) and descending (newest first) order. We'll make copies of the array first to avoid mutating the original state (a React best practice):

// Sort by date: oldest to newest
const sortByDateAsc = (array) => {
  return [...array].sort((a, b) => {
    const dateA = parseDateString(a.time);
    const dateB = parseDateString(b.time);
    return dateA - dateB; // Subtract dates to get time difference in ms
  });
};

// Sort by date: newest to oldest
const sortByDateDesc = (array) => {
  return [...array].sort((a, b) => {
    const dateA = parseDateString(a.time);
    const dateB = parseDateString(b.time);
    return dateB - dateA;
  });
};

Step 3: Use in a React Component

Now let's integrate this into a React component. We'll use useMemo to cache the sorted array so we don't re-sort on every render (boosts performance), and add a toggle to switch between sort orders:

import { useState, useEffect, useMemo } from 'react';

const DeveloperList = () => {
  const [developers, setDevelopers] = useState([]);
  const [sortOrder, setSortOrder] = useState('desc'); // Default to newest first

  // Simulate API data fetch
  useEffect(() => {
    const fetchDeveloperData = async () => {
      // Replace this with your actual API call
      const apiResponse = [
        { 
          id: '1', 
          developer: { 
            name: 'Michelle Stewart', 
            proff: 'Account', 
            shortInfo: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit...',
            mail: 'michellestewart@gmail.com', 
            phone: '+48 500 400 300', 
            adress: '65 Lorem St, Warsaw, PL', 
            company: 'Symu.co', 
            isOnline: false 
          },
          time: 'Today, 5:32 PM',
          devmessages: [ { time: '10 April 2018', message: 'Lorem ipsum dolor sit amet...' } ]
        },
        { 
          id: '2', 
          developer: { 
            name: 'John Doe', 
            proff: 'Developer', 
            shortInfo: 'Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris...',
            mail: 'johndoe@example.com', 
            phone: '+48 123 456 789', 
            adress: '123 Ipsum Ave, Krakow, PL', 
            company: 'DevCorp', 
            isOnline: true 
          },
          time: '10 April 2018',
          devmessages: [ { time: '9 April 2018', message: 'Dolor sit amet, consectetur adipiscing...' } ]
        }
      ];
      setDevelopers(apiResponse);
    };

    fetchDeveloperData();
  }, []);

  // Memoize sorted array to avoid unnecessary re-renders
  const sortedDevelopers = useMemo(() => {
    return sortOrder === 'asc' 
      ? sortByDateAsc(developers) 
      : sortByDateDesc(developers);
  }, [developers, sortOrder]);

  return (
    <div className="developer-list">
      <button 
        onClick={() => setSortOrder(prev => prev === 'asc' ? 'desc' : 'asc')}
        style={{ marginBottom: '1rem' }}
      >
        Toggle Sort: {sortOrder === 'asc' ? 'Oldest First' : 'Newest First'}
      </button>
      <ul>
        {sortedDevelopers.map(dev => (
          <li key={dev.id} style={{ marginBottom: '1.5rem', padding: '1rem', border: '1px solid #eee' }}>
            <h3>{dev.developer.name}</h3>
            <p><strong>Last Active:</strong> {dev.time}</p>
            <p><strong>Role:</strong> {dev.developer.proff}</p>
          </li>
        ))}
      </ul>
    </div>
  );
};

export default DeveloperList;

Key Notes

  • Avoid Mutation: We use [...array] to create a copy of the original array before sorting, since Array.sort() mutates the array in place—this keeps our React state predictable.
  • Performance: useMemo ensures we only re-sort when the developers array or sortOrder changes, instead of on every component render.
  • Edge Cases: If your API returns other date formats (like "Yesterday" or different time zones), you can extend the parseDateString function to handle those. You might also want to add checks for invalid dates (e.g., if (isNaN(dateA.getTime()))) to handle unexpected data gracefully.

内容的提问来源于stack exchange,提问作者Вова Магдич

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:55:39