这里包含名称和更新的TimeStamp 属性的阵列。我想根据 updatedTimeStamp 属性对阵列进行排序。
所以我在此使用date-fns库,我只想使用这个库,我可以不用这个库,但这是我使用这个库的要求。
我可以根据updatedTimeStamp 进行排序,但它不回传名称如何将name 属性与updatedTimeStamp 一起回传。
import { compareDesc } from "date-fns";
let arr = [
{
name:"abc",
updatedTimeStamp: "2021-12-06 14:09:00.304464"
},
{
name:"xyz",
updatedTimeStamp: "2021-12-14 13:41:58.708262"
},
{
name:"thomas",
updatedTimeStamp: "2021-12-06 15:39:09.365793"
},
{
name:"Robin",
updatedTimeStamp: "2021-12-14 09:15:42.141081"
},
{
name:"Jobin",
updatedTimeStamp: "2021-12-14 12:50:29.723421"
},
{
name:"Tobin",
}
];
const objArr = arr.map(i => i.updatedTimeStamp).sort(compareDesc)
uj5u.com热心网友回复:
我会这样做。您可以传递自己的函式,该函式回传 comparsefunc
import {
compareDesc
} from "date-fns";
let arr = [{
name: "abc",
updatedTimeStamp: "2021-12-06 14:09:00.304464"
},
{
name: "xyz",
updatedTimeStamp: "2021-12-14 13:41:58.708262"
},
{
name: "thomas",
updatedTimeStamp: "2021-12-06 15:39:09.365793"
},
{
name: "Robin",
updatedTimeStamp: "2021-12-14 09:15:42.141081"
},
{
name: "Jobin",
updatedTimeStamp: "2021-12-14 12:50:29.723421"
}
];
// careful since this modifies the original array
arr.sort((a, b) => compareDesc(a.updatedTimeStamp, b.updatedTimeStamp))
// to not mutate the original you can do this
const objArr = [...arr].sort((a, b) => compareDesc(a.updatedTimeStamp, b.updatedTimeStamp))
uj5u.com热心网友回复:
我可以不用这个库,但这是我使用这个库的要求。
为什么?您可以使用正常的内置排序对您拥有的日期格式进行排序
let arr = [
{
name:"abc",
updatedTimeStamp: "2021-12-06 14:09:00.304464"
},
{
name:"xyz",
updatedTimeStamp: "2021-12-14 13:41:58.708262"
},
{
name:"thomas",
updatedTimeStamp: "2021-12-06 15:39:09.365793"
},
{
name:"Robin",
updatedTimeStamp: "2021-12-14 09:15:42.141081"
},
{
name:"Jobin",
updatedTimeStamp: "2021-12-14 12:50:29.723421"
},
{
name:"Tobin",
}
];
const objArr = arr.slice(0).sort((a,b) => {
if (a.updatedTimeStamp > b.updatedTimeStamp) return 1
if (a.updatedTimeStamp < b.updatedTimeStamp) return -1
return 0
})
console.log(objArr)
0 评论