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
相关产品推荐
相关产品推荐

