猿问

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

我有一个数组对象


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 月,依此类推,


慕神8447489
浏览 154回答 2
2回答

智慧大石

您需要提供自定义比较器函数.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 functionfunction 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#reduceconst 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);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答