在 JavaScript 中编写日期和名称的排序?
Write sorting for date and name in JavaScript?
如何在javascript中编写日期和姓名的排序?我有一个 table。有 2 列:name
和 created date
:
name: ["A", "A9", "A10", "A11", "A3"]
createdDate: ["Apr 2, 2019 3:07 PM", "Apr 10, 2019 9:25 AM", "Apr 30, 2019 6:08 PM", "Apr 10, 2019 8:25 AM", "Apr 2, 2019 8:07 PM"]
我已经尝试使用排序方法。输出应该是这样的:
name: ["A", "A3", "A9", "A10", "A11"]
createdDate: ["Apr 2, 2019 3:07 PM", "Apr 2, 2019 8:07 PM","Apr 10, 2019 8:25 AM", "Apr 10, 2019 9:25 AM", "Apr 30, 2019 6:08 PM"]
对字符串进行排序:
array.sort(function(a, b) {
var titleA = a.title.toLowerCase(), titleB = b.title.toLowerCase();
if (titleA < titleB) return -1;
if (titleA > titleB) return 1;
return 0;
});
要对日期进行排序:
array.sort(function(a, b) {
var dateA = new Date(a.release), dateB = new Date(b.release);
return dateA - dateB;
});
有关详细信息,请参阅此文档https://en.proft.me/2015/11/14/sorting-array-objects-number-string-date-javascrip/。
这是使用 localeCompare() 并将数字作为选项之一按字母数字对 name
数组进行排序的方法。
const name = ["A", "A9", "A10", "A11", "A3"];
name.sort((a, b) => a.localeCompare(b, 'en', { numeric: true }));
console.log(name);
这是按日期排序的方法。本质上,我们在进行比较时将它们转换为 JavaScript 日期对象。
const createdDate = ["Apr 2, 2019 3:07 PM", "Apr 2, 2019 8:07 PM","Apr 10, 2019 8:25 AM", "Apr 10, 2019 9:25 AM", "Apr 30, 2019 6:08 PM"];
createdDate.sort((a, b) => new Date(a) - new Date(b));
console.log(createdDate);
为了正确地做到这一点,我会结合 and
的答案
字符串:
name.sort((a, b) => a.localeCompare(b, 'en', { numeric: true }));
日期:
createdDate.sort((a, b) => Date.parse(a) - Date.parse(b));
如何在javascript中编写日期和姓名的排序?我有一个 table。有 2 列:name
和 created date
:
name: ["A", "A9", "A10", "A11", "A3"]
createdDate: ["Apr 2, 2019 3:07 PM", "Apr 10, 2019 9:25 AM", "Apr 30, 2019 6:08 PM", "Apr 10, 2019 8:25 AM", "Apr 2, 2019 8:07 PM"]
我已经尝试使用排序方法。输出应该是这样的:
name: ["A", "A3", "A9", "A10", "A11"]
createdDate: ["Apr 2, 2019 3:07 PM", "Apr 2, 2019 8:07 PM","Apr 10, 2019 8:25 AM", "Apr 10, 2019 9:25 AM", "Apr 30, 2019 6:08 PM"]
对字符串进行排序:
array.sort(function(a, b) {
var titleA = a.title.toLowerCase(), titleB = b.title.toLowerCase();
if (titleA < titleB) return -1;
if (titleA > titleB) return 1;
return 0;
});
要对日期进行排序:
array.sort(function(a, b) {
var dateA = new Date(a.release), dateB = new Date(b.release);
return dateA - dateB;
});
有关详细信息,请参阅此文档https://en.proft.me/2015/11/14/sorting-array-objects-number-string-date-javascrip/。
这是使用 localeCompare() 并将数字作为选项之一按字母数字对 name
数组进行排序的方法。
const name = ["A", "A9", "A10", "A11", "A3"];
name.sort((a, b) => a.localeCompare(b, 'en', { numeric: true }));
console.log(name);
这是按日期排序的方法。本质上,我们在进行比较时将它们转换为 JavaScript 日期对象。
const createdDate = ["Apr 2, 2019 3:07 PM", "Apr 2, 2019 8:07 PM","Apr 10, 2019 8:25 AM", "Apr 10, 2019 9:25 AM", "Apr 30, 2019 6:08 PM"];
createdDate.sort((a, b) => new Date(a) - new Date(b));
console.log(createdDate);
为了正确地做到这一点,我会结合
字符串:
name.sort((a, b) => a.localeCompare(b, 'en', { numeric: true }));
日期:
createdDate.sort((a, b) => Date.parse(a) - Date.parse(b));