我在表中列出了用户列表。 活跃用户应排在非活跃用户之上。
我正在尝试使用 lodash sortBy
函数进行此排序
,但没有成功。
这是 userArray
的样子:
const userArray [
{
// I need to show users which have disabled = false first
// and then users with disabled = true
disabled: true, // <==========
email: "hgaither@cmregent.com",
firstName: "Harriet",
lastName: "Gaither",
role: "claimsHandlerSupervisor",
userId: "03VFpxtMWgY1jKDHDLcrWSw1qzx1",
},
{
disabled: false, // <===========
email: "hgaither@cmregent.com",
firstName: "Harriet",
lastName: "Gaither",
role: "claimsHandlerSupervisor",
userId: "03VFpxtMWgY1jKDHDLcrWSw1qzx1",
},
]
这是带有用户数组和 sortBy loadsh 函数的代码的代码笔: https://codepen.io/nikolatrajkovicq/pen/pGXdpM?editors=1112
欢迎任何建议。
最佳答案
您可以使用 sort
像这样:
const userArray=[{disabled:true,email:"hgaither@cmregent.com",firstName:"Harriet",lastName:"Gaither",role:"claimsHandlerSupervisor",userId:"03VFpxtMWgY1jKDHDLcrWSw1qzx1",},{disabled:false,email:"hgaither@cmregent.com",firstName:"Harriet",lastName:"Gaither",role:"claimsHandlerSupervisor",userId:"03VFpxtMWgY1jKDHDLcrWSw1qzx1",},]
userArray.sort((a,b) => a.disabled - b.disabled)
console.log(userArray)
您可以只减去 compareFunction
中的 bool 属性。这是因为强制
true - false === 1
false - true === -1
true - true === 0
关于javascript - 如何根据 bool 属性对对象数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54826537/