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

JavaScript如何实现数组按日期与字母复合排序,解决日期排序失效问题

数组排序解决方案

你的需求是按品牌字母正序+创建日期倒序实现多级排序,之前日期排序失效大概率是没有正确将日期字符串转换为可比较的时间格式,或者排序优先级配置错误。

核心实现逻辑

  • 第一排序维度:品牌(brand)按字母升序排列,使用localeCompare方法实现自然字母排序
  • 第二排序维度:同品牌下按创建日期(createdDate)降序排列,将ISO格式的日期字符串转换为时间戳后比较

可直接运行的代码示例

// 目标数组
const productList = [{
    productId: 21,
    title: "Huawei P40 Lite ",
    brand: "Huawei",
    price: 120,
    discountPercentage: 10,
    color: "Black",
    createdDate: "2021-01-15T01:00:00+03:00",
  },
  {
    productId: 22,
    title: "Huawei P40 Lite",
    brand: "Huawei",
    price: 1026,
    discountPercentage: 0,
    color: "Green",
    createdDate: "2021-01-16T01:00:00+03:00",
  },
  {
    productId: 23,
    title: "Apple iPhone 11",
    brand: "Apple",
    price: 1220,
    discountPercentage: 11,
    color: "White",
    createdDate: "2021-01-17T01:00:00+03:00",
  },
 {
    productId: 24,
    title: "Apple iPhone 12",
    brand: "Apple",
    price: 1420,
    discountPercentage: 11,
    color: "White",
    createdDate: "2021-01-18T01:00:00+03:00",
  }]

// 排序函数
const sortedList = productList.sort((a, b) => {
  // 第一优先级:品牌字母升序
  const brandCompare = a.brand.localeCompare(b.brand)
  if (brandCompare !== 0) {
    return brandCompare
  }
  // 第二优先级:同品牌下日期倒序
  return new Date(b.createdDate).getTime() - new Date(a.createdDate).getTime()
})

console.log(sortedList)

排序结果验证

执行后输出的结果和你预期的完全一致:Apple品牌的商品排在最前,同品牌下创建时间越新的越靠前,之后是Huawei品牌的商品,同样按创建时间倒序排列。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 23:45:03