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

如何在JavaScript中按当前月份排序含created_at的Laravel对象数组?

按当前月份排序数组的实现方案

嘿,我来帮你搞定这个需求!你要给包含Laravel created_at 字段的数组按当前月份排序,其实不管用原生JS还是Lodash都能轻松实现,我给你详细拆解下思路和代码:

核心思路

要实现这个排序,我们需要:

  • 先获取当前年份和月份(注意JS的月份是从0开始的,所以要加1转成实际的1-12月份)
  • 制定排序规则:优先把属于当前年月的项排在前面;如果都是当前年月的,再按created_at的时间先后排序;非当前年月的项可以按时间逻辑调整顺序(比如倒序/正序)

原生JavaScript实现

直接用数组的sort()方法就能搞定,代码示例如下:

var arr = [{ "id": 1, "user_id": 1, "roi": 90, "sport": "Biatlon", "created_at": "2017-12-29 11:42:40", "user": { "id": 1, "userName": "iamsadek", "profilePic": "90TyP1Rkn2WI4T5VQmqmJJPB5cAY8BMrUim1WJT0.png" } }, { "id": 5, "user_id": 2, "roi": 30, "sport": "Atletika", "created_at": "2018-01-10 22:20:06", "user": { "id": 2, "userName": "hkmsadek", "profilePic": "pic.png" } }, { "id": 4, "user_id": 5, "roi": 10, "sport": "Biatlon", "created_at": "2018-01-10 17:11:45", "user": { "id": 5, "userName": "deil", "profilePic": "L8KIW0gXXmi5QALnAHjksCdg4tcUK9cx5jn84nrk.jpeg" } }];

// 获取当前年份和月份
const now = new Date();
const currentYear = now.getFullYear();
const currentMonth = now.getMonth() + 1;

// 自定义排序函数
arr.sort((a, b) => {
    // 将created_at字符串转为Date对象
    const dateA = new Date(a.created_at);
    const dateB = new Date(b.created_at);
    
    // 提取每项的年份和月份
    const yearA = dateA.getFullYear();
    const monthA = dateA.getMonth() + 1;
    const yearB = dateB.getFullYear();
    const monthB = dateB.getMonth() + 1;
    
    // 优先判断是否为当前年月:当前年月的项排前面
    const isCurrentA = yearA === currentYear && monthA === currentMonth;
    const isCurrentB = yearB === currentYear && monthB === currentMonth;
    
    if (isCurrentA && !isCurrentB) return -1; // A是当前月,B不是,A靠前
    if (!isCurrentA && isCurrentB) return 1;  // B是当前月,A不是,B靠前
    
    // 若都是当前月,按时间先后排序(旧的在前;要新的在前就换成 dateB - dateA)
    return dateA - dateB;
});

console.log(arr);

Lodash实现方案

如果你想用Lodash,可以用_.orderBy()来实现多条件排序,代码更简洁:

const _ = require('lodash'); // 确保已引入Lodash

const now = new Date();
const currentYear = now.getFullYear();
const currentMonth = now.getMonth() + 1;

// 多条件排序:先按是否为当前月分组,再按时间排序
const sortedArr = _.orderBy(arr, [
    // 第一个条件:标记是否为当前月(是=0,不是=1,0会排在前面)
    item => {
        const date = new Date(item.created_at);
        return (date.getFullYear() === currentYear && date.getMonth() + 1 === currentMonth) ? 0 : 1;
    },
    // 第二个条件:按created_at时间排序
    item => new Date(item.created_at)
], ['asc', 'asc']); // 第一个条件升序(当前月在前),第二个条件升序(旧的在前)

console.log(sortedArr);

额外小技巧

如果你的需求是只筛选出当前月份的项,可以先加个filter():

const currentMonthItems = arr.filter(item => {
    const date = new Date(item.created_at);
    return date.getFullYear() === currentYear && date.getMonth() + 1 === currentMonth;
});

内容的提问来源于stack exchange,提问作者Hkm Sadek

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:57:26