在React JS中按日期对数组进行排序
我有一个对象数组,如下所示:
let cars = [ {"id":20,"mileage":41300,"make":"Golf", initialRegistration:"09/02/2010"},
{"id":21,"mileage":51300,"make":"Passat", initialRegistration:"06/04/2012"},
{"id":22,"mileage":61300,"make":"Audi", initialRegistration:"02/01/2018"},
{"id":23,"mileage":20300,"make":"Touran", initialRegistration:"17/09/2013"},
{"id":24,"mileage":10300,"make":"Polo", initialRegistration:"26/07/2014"}
];
我想按排序initialRegistration
。
我尝试这样做如下:
let sortedCars = cars.sort((a, b) => Date.parse(a.initialRegistration) - Date.parse(b.initialRegistration));let sortedCars1 = cars.sort((a, b) => new Date(a.initialRegistration) - new Date(b.initialRegistration));
let sortedCars2 = cars.sort((a, b) => new Date(a.initialRegistration).getTime() - new Date(b.initialRegistration).getTime());
但是这些尝试都没有成功。我得到的结果是:
Golf - 09/02/2010Passat - 06/04/2012
Audi - 02/01/2018
Touran - 17/09/2013
Polo - 26/07/2014
这是小提琴。
回答:
使用Date
构造函数并执行类似的操作。
let sortedCars1 = cars.sort((a, b) => new Date(...a.initialRegistration.split('/').reverse()) - new Date(...b.initialRegistration.split('/').reverse()));let cars = [{
"id": 20,
"mileage": 41300,
"make": "Golf",
initialRegistration: "09/02/2010"
}, {
"id": 21,
"mileage": 51300,
"make": "Passat",
initialRegistration: "06/04/2012"
}, {
"id": 22,
"mileage": 61300,
"make": "Audi",
initialRegistration: "02/01/2018"
}, {
"id": 23,
"mileage": 20300,
"make": "Touran",
initialRegistration: "17/09/2013"
}, {
"id": 24,
"mileage": 10300,
"make": "Polo",
initialRegistration: "26/07/2014"
}];
let sortedCars1 = cars.sort((a, b) => new Date(...a.initialRegistration.split('/').reverse()) - new Date(...b.initialRegistration.split('/').reverse()));
console.log(sortedCars1);
或通过String#localeCompare
将日期字符串反转后使用字符串比较。
let sortedCars1 = cars.sort((a, b) => a.initialRegistration.split('/').reverse().join().localeCompare(b.initialRegistration.split('/').reverse().join()));
let cars = [{
"id": 20,
"mileage": 41300,
"make": "Golf",
initialRegistration: "09/02/2010"
}, {
"id": 21,
"mileage": 51300,
"make": "Passat",
initialRegistration: "06/04/2012"
}, {
"id": 22,
"mileage": 61300,
"make": "Audi",
initialRegistration: "02/01/2018"
}, {
"id": 23,
"mileage": 20300,
"make": "Touran",
initialRegistration: "17/09/2013"
}, {
"id": 24,
"mileage": 10300,
"make": "Polo",
initialRegistration: "26/07/2014"
}];
let sortedCars1 = cars.sort((a, b) =>
a.initialRegistration.split('/').reverse().join().localeCompare(b.initialRegistration.split('/').reverse().join()));
console.log(sortedCars1);
以上是 在React JS中按日期对数组进行排序 的全部内容, 来源链接: utcz.com/qa/429887.html