如何在JavaScript中对日期数组进行排序
假设我们有一个包含一些像这样的日期的数组-
const arr = [[ '02/13/2015', 0.096 ],
[ '11/15/2013', 0.189 ],
[ '05/15/2014', 0.11 ],
[ '12/13/2013', 0.1285 ],
[ '01/15/2013', 0.12 ],
[ '01/15/2014', 0.11 ],
[ '02/14/2014', 0.11 ],
[ '03/14/2014', 0.11 ],
[ '01/15/2015', 0.096 ],
[ '07/15/2015', 0.096 ],
[ '04/15/2013', 0.12 ],
[ '04/15/2014', 0.11 ],
[ '05/15/2013', 0.12 ],
[ '06/14/2013', 0.12 ],
[ '06/16/2014', 0.11 ],
[ '07/15/2013', 0.12 ],
[ '07/15/2014', 0.11 ],
[ '03/16/2015', 0.096 ]
];
我们需要编写一个JavaScript函数,该函数接受一个这样的数组,并根据每个数组中的日期以升序对数组进行排序。
示例
以下是代码-
const arr = [[ '02/13/2015', 0.096 ],
[ '11/15/2013', 0.189 ],
[ '05/15/2014', 0.11 ],
[ '12/13/2013', 0.1285 ],
[ '01/15/2013', 0.12 ],
[ '01/15/2014', 0.11 ],
[ '02/14/2014', 0.11 ],
[ '03/14/2014', 0.11 ],
[ '01/15/2015', 0.096 ],
[ '07/15/2015', 0.096 ],
[ '04/15/2013', 0.12 ],
[ '04/15/2014', 0.11 ],
[ '05/15/2013', 0.12 ],
[ '06/14/2013', 0.12 ],
[ '06/16/2014', 0.11 ],
[ '07/15/2013', 0.12 ],
[ '07/15/2014', 0.11 ],
[ '03/16/2015', 0.096 ]
];
const sortByDate = arr => {
const sorter = (a, b) => {
return new Date(a[0]) - new Date(b[0]);
};
arr.sort(sorter);
};
sortByDate(arr);
console.log(arr);
输出结果
这将在控制台上产生以下输出-
[[ '01/15/2013', 0.12 ],
[ '04/15/2013', 0.12 ],
[ '05/15/2013', 0.12 ],
[ '06/14/2013', 0.12 ],
[ '07/15/2013', 0.12 ],
[ '11/15/2013', 0.189 ],
[ '12/13/2013', 0.1285 ],
[ '01/15/2014', 0.11 ],
[ '02/14/2014', 0.11 ],
[ '03/14/2014', 0.11 ],
[ '04/15/2014', 0.11 ],
[ '05/15/2014', 0.11 ],
[ '06/16/2014', 0.11 ],
[ '07/15/2014', 0.11 ],
[ '01/15/2015', 0.096 ],
[ '02/13/2015', 0.096 ],
[ '03/16/2015', 0.096 ],
[ '07/15/2015', 0.096 ]
]
以上是 如何在JavaScript中对日期数组进行排序 的全部内容, 来源链接: utcz.com/z/330956.html