按年和月对 JavaScript 数组进行排序
我们有一个这样的数组 −
const arr = [{ year: 2020, month: 'January' }, { year: 2017, month: 'March' }, { year: 2010, month: 'January' }, { year: 2010, month: 'December' }, { year: 2020, month: 'April' }, { year: 2017, month: 'August' }, { year: 2010, month: 'February' }, { year: 2020, month: 'October' }, { year: 2017, month: 'June' }]
我们必须按升序(升序)对该数组按年份进行排序。此外,如果存在两个具有相同年份属性的对象,则我们必须按月份(如一月、二月、三月等)对这些年份进行排序。
所以,让我们编写这个排序问题的代码。其完整代码如下 −
示例
const arr = [{ year: 2020, month: 'January' }, { year: 2017, month: 'March' }, { year: 2010, month: 'January' }, { year: 2010, month: 'December' }, { year: 2020, month: 'April' }, { year: 2017, month: 'August' }, { year: 2010, month: 'February' }, { year: 2020, month: 'October' }, { year: 2017, month: 'June' }] const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; const sorter = (a, b) => { if(a.year !== b.year){ return a.year - b.year; }else{ return months.indexOf(a.month) - months.indexOf(b.month); }; }; arr.sort(sorter); console.log(arr);
我们检查年份是否不同,我们只需按年份对它们进行排序,但当年份相同,我们检查月份从我们定义的自定义月份数组获得帮助,并且通过这种方式,具有相同年份的对象按月份进行排序。
输出
控制台中的输出将是 −
[ { year: 2010, month: 'January' }, { year: 2010, month: 'February' }, { year: 2010, month: 'December' }, { year: 2017, month: 'March' }, { year: 2017, month: 'June' }, { year: 2017, month: 'August' }, { year: 2020, month: 'January' }, { year: 2020, month: 'April' }, { year: 2020, month: 'October' } ]
广告