首页 > 解决方案 > 基于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"}]]

标签: javascriptarrays

解决方案


您可以先检查长度,然后按日期字符串排序。

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; }


推荐阅读