为了账号安全,请及时绑定邮箱和手机立即绑定

如何根据javascript中的多个字段对数组进行排序

如何根据javascript中的多个字段对数组进行排序

慕神8447489 2021-06-30 14:57:57
我有一个数组对象events = [   {     year: "2019",     month: "June",     title: "title",     desc: "desc"   },   {     year: "2019",     month: "June",     title: "title",     desc: "desc"    },    {      year: "2019",      month: "July",      title: "title",      desc: "desc"    },    {      year: "2018",      month: "June",      title: "title",      desc: "desc"     },     {       year: "2018",       month: "March",       title: "title",       desc: "desc"     },     {       year: "2018",       month: "March",       title: "title",       desc: "desc"      }    ]如何对数组进行排序以显示相似的年份和月份,我需要在反应组件中使用它,例如一行将显示 2019 年 6 月和 2019 年 7 月,然后是 2018 年 6 月,依此类推,
查看完整描述

2 回答

?
智慧大石

TA贡献1946条经验 获得超3个赞

您需要提供自定义比较器函数.sort以使用月份和年份进行排序。


const events = [

   {

     year: "2019",

     month: "June",

     title: "title",

     desc: "desc"

   },

   {

     year: "2019",

     month: "June",

     title: "title",

     desc: "desc"

    },

    {

      year: "2019",

      month: "July",

      title: "title",

      desc: "desc"

    },

    {

      year: "2018",

      month: "June",

      title: "title",

      desc: "desc"

     },

     {

       year: "2018",

       month: "March",

       title: "title",

       desc: "desc"

     },

     {

       year: "2018",

       month: "March",

       title: "title",

       desc: "desc"

      }

];


// Custom comparator function

function sortByMonthYear(a, b) {

    const keyA = `${a.month} ${a.year}`;

    const keyB = `${b.month} ${b.year}`;

    

    if (keyA.localeCompare(keyB)) {

        return -1;

    }

    else if (keyA === keyB) {

        return 0;

    }

    return 1;

}



const grouping = events.sort(sortByMonthYear);


console.log(grouping);

更新:


您还可以使用 Array#prototype#reduce


const events = [{

    year: "2019",

    month: "June",

    title: "title",

    desc: "desc"

  },

  {

    year: "2019",

    month: "June",

    title: "title",

    desc: "desc"

  },

  {

    year: "2019",

    month: "July",

    title: "title",

    desc: "desc"

  },

  {

    year: "2018",

    month: "June",

    title: "title",

    desc: "desc"

  },

  {

    year: "2018",

    month: "March",

    title: "title",

    desc: "desc"

  },

  {

    year: "2018",

    month: "March",

    title: "title",

    desc: "desc"

  }

];


const grouping = events.reduce((acc, curr) => {

  const key = `${curr.month} ${curr.year}`;

  if (!acc[key]) {

    acc[key] = [curr];

  } else {

    acc[key].push(curr);

  }

  return acc;

}, {});


console.log(grouping);


查看完整回答
反对 回复 2021-07-01
  • 2 回答
  • 0 关注
  • 153 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信