javascript - 基于javascript中的数组长度和数组值(日期格式)对数组进行排序?
问题描述
我有一个场景,我有一个包含对象的数组数组,我需要对数组进行排序,其中长度为 1 的内部数组显示在顶部,长度大于 1 的内部数组根据对象内部的值进行排序。
let a = [[{c:"11-01-2020"}], [{c:"12-01-2020"}, {c:"12-01-2020"}], [{c:"13-01-2020"}, {c:"13-01-2020"}], [{c:"14-01-2020"}]]
function sortfn(a, b) {
if (a.length === 1 && b.length === 1) {
return 0;
}
if (a.length === 1 ||
(a[0].c > b[0].c) &&
a.length !== 1 &&
b.length !== 1
) {
return -1;
}
return 1;
}
a.sort(sortfn);
console.log(a)
结果应该是
[[{c:"11-01-2020"}], [{c:"14-01-2020"}]], [{c:"13-01-2020"}, {c:"13-01-2020"}], [{c:"12-01-2020"}, {c:"12-01-2020"}]]
解决方案
您可以先检查长度,然后按日期字符串排序。
const
getISODate = custom => custom.replace(/^(\d{2})-(\d{2})-(\d{4})$/, '$3-$2-$1'),
sortFn = (a, b) => (b.length === 1) - (a.length === 1) || getISODate(a[0].c).localeCompare(getISODate(b[0].c)),
array = [[{ c: "11-01-2020" }], [{ c: "12-01-2020" }, { c: "12-01-2020" }], [{ c: "13-01-2020" }, { c: "13-01-2020" }], [{ c: "14-01-2020" }]]
array.sort(sortFn);
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
推荐阅读
- r - 使用 plm 估计模型规范之间的范围内
- javascript - 列表在网页中不可点击。关于可能出现问题的任何建议?
- javascript - Next.js 动态路由 - 页面重新加载或直接调用动态路由时出现 404
- python - For loops with multiple result
- c# - Is there a difference between "double val = 1;" and "double val = 1D;"?
- c++ - C++ how to add an element to a pointer array by exceeding size
- ionic-framework - Ionic 3 to Ionic 4 SCSS migration
- java - Primary key values are getting updated in Spring boot
- multithreading - Cython prange with function reading from numpy array (memoryview) freezes, why?
- php - 从具有混合格式的列中提取包大小