按年份和月份对数组排序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' }]
我们必须根据年份以升序(升序)对数组进行排序。而且,如果存在两个具有相同year属性的对象,那么我们就必须根据月份对这些年份进行排序(例如jan,然后是feb,然后是三月,依此类推)。
因此,让我们为该排序问题编写代码。完整的代码将是-
示例
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' } ]