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

使用Lodash对按年份分组后的对象数组进行排序

使用Lodash按年份分组并排序对象数组

没问题,我来帮你一步步实现这个需求!我们会先按年份分组数据,再对分组结果进行排序,全程用Lodash来简化操作。

步骤1:按年份分组数据

首先,我们需要从每个对象的date字段中提取年份,然后用_.groupBy来分组。这里直接通过原生Date对象的getFullYear()方法获取年份即可:

const _ = require('lodash');

const data = [
  { id: 1, amount: 2000, date: "2018-01-31T00:00:00.000Z" },
  { id: 2, amount: 3000, date: "2017-07-31T00:00:00.000Z" },
  { id: 3, amount: 6000, date: "2018-01-31T00:00:00.000Z" },
  { id: 4, amount: 7000, date: "2017-01-31T00:00:00.000Z" },
  { id: 5, amount: 5000, date: "2017-03-31T00:00:00.000Z" },
  { id: 6, amount: 3000, date: "2018-02-22T00:00:00.000Z" },
  { id: 7, amount: 4500, date: "2017-01-31T00:00:00.000Z" }
];

// 按年份分组,键为数字类型的年份
const groupedByYear = _.groupBy(data, item => new Date(item.date).getFullYear());

console.log(groupedByYear);
// 输出:
// {
//   2017: [ {...}, {...}, {...}, {...} ],
//   2018: [ {...}, {...}, {...} ]
// }

步骤2:对分组结果排序

_.groupBy返回的是普通对象,默认键的顺序不固定。我们可以把它转成键值对数组,排序后再根据需求选择保留数组形式或转回对象:

方式1:得到有序数组(推荐,结构更直观)

如果你希望得到按年份排序的数组,每个元素包含年份和对应的数据,用_.toPairs转成数组后,再用_.sortBy排序:

// 按年份升序排序
const sortedGroupsAsc = _.sortBy(_.toPairs(groupedByYear), pair => pair[0]);

console.log(sortedGroupsAsc);
// 输出:
// [
//   [2017, [ {...}, {...}, {...}, {...} ]],
//   [2018, [ {...}, {...}, {...} ]]
// ]

// 按年份降序排序,只需给排序字段加负号
const sortedGroupsDesc = _.sortBy(_.toPairs(groupedByYear), pair => -pair[0]);

方式2:转回有序对象

如果你还是需要对象格式(ES6+中对象会保留插入顺序),可以用_.fromPairs把排序后的数组转回对象:

// 升序排序后转回对象
const sortedGroupsObject = _.fromPairs(sortedGroupsAsc);

console.log(sortedGroupsObject);
// 输出的对象键会按2017、2018的顺序排列

额外小技巧:分组时同时处理组内数据

如果还需要对每个年份组内的对象(比如按日期或金额)排序,可以在分组后链式调用_.mapValues处理:

// 分组后,每个年份组内的对象按date升序排序
const groupedAndSortedInner = _.mapValues(groupedByYear, items => 
  _.sortBy(items, item => new Date(item.date))
);

这样整个流程就完全满足你的需求了,你可以根据实际场景选择合适的排序输出形式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:22:57