You need to enable JavaScript to run this app. 如何按对象subCateg属性分组数组,按日期收集count生成指定结构
优惠活动
大模型
产品
解决方案
定价
更多

如何按对象subCateg属性分组数组,按日期收集count生成指定结构

实现步骤

  1. 先提取原数组中所有不重复的日期,按时间先后排序,确定最终data数组的元素顺序
  2. 遍历原数组,按subCateg分组,存储每个分类下不同日期对应的count值
  3. 对每个分类,按排序好的日期序列填充data数组,对应日期无数据的位置补0

代码实现

// 原数组
var arr = [
  { count: 27, dataRil: "08/06/21", subCateg: "FISH" },
  { count: 22, dataRil: "08/06/21", subCateg: "DOG" },
  { count: 28, dataRil: "09/06/21", subCateg: "FISH" },
  { count: 18, dataRil: "09/06/21", subCateg: "DOG" },
  { count: 1, dataRil: "09/06/21", subCateg: "CAT" },
  { count: 1, dataRil: "09/06/21", subCateg: "BIRD" },
];

// 步骤1:获取去重且按时间升序排列的日期数组
const dateSet = new Set();
arr.forEach(item => dateSet.add(item.dataRil));
// 把日期字符串转成时间戳排序,避免字符串排序异常
const sortedDates = Array.from(dateSet).sort((a, b) => new Date(a) - new Date(b));

// 步骤2:按subCateg分组存储日期对应的count
const categMap = {};
arr.forEach(item => {
  if (!categMap[item.subCateg]) {
    categMap[item.subCateg] = {};
  }
  categMap[item.subCateg][item.dataRil] = item.count;
});

// 步骤3:生成目标datasets数组
const datasets = Object.keys(categMap).map(label => {
  // 按排序后的日期顺序填充data,不存在则补0
  const data = sortedDates.map(date => categMap[label][date] || 0);
  return { label, data };
});

console.log(datasets);

代码运行后输出的datasets完全匹配你需要的结构,后续新增日期也会自动适配排序逻辑,无需手动调整位置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 15:45:05