我在表中列出了用户列表.活跃用户应该排在非活跃用户之上.
I have list of users presented in table. Active users should be sorted above the inactive users.
我正在尝试使用 lodash sortBy 函数来制作这个 sort,但没有成功.
I am trying to make this sort using lodash sortBy function, but unsuccessfully.
这里是 userArray 的样子:
const userArray [ { // I need to show users which have disabled = false first // and then users with disabled = true disabled: true, // <========== email: "hgaither@cmregent", firstName: "Harriet", lastName: "Gaither", role: "claimsHandlerSupervisor", userId: "03VFpxtMWgY1jKDHDLcrWSw1qzx1", }, { disabled: false, // <=========== email: "hgaither@cmregent", firstName: "Harriet", lastName: "Gaither", role: "claimsHandlerSupervisor", userId: "03VFpxtMWgY1jKDHDLcrWSw1qzx1", }, ]这是带有用户数组和 sortBy loadsh 函数的代码笔:codepen.io/nikolatrajkovicq/pen/pGXdpM?editors=1112
here is code pen with code with users array and sortBy loadsh function: codepen.io/nikolatrajkovicq/pen/pGXdpM?editors=1112
欢迎任何建议.
推荐答案您可以使用 sort 像这样:
You can use sort like this:
const userArray=[{disabled:true,email:"hgaither@cmregent",firstName:"Harriet",lastName:"Gaither",role:"claimsHandlerSupervisor",userId:"03VFpxtMWgY1jKDHDLcrWSw1qzx1",},{disabled:false,email:"hgaither@cmregent",firstName:"Harriet",lastName:"Gaither",role:"claimsHandlerSupervisor",userId:"03VFpxtMWgY1jKDHDLcrWSw1qzx1",},] userArray.sort((a,b) => a.disabled - b.disabled) console.log(userArray)您可以只减去 compareFunction 中的布尔属性.这是因为强制
You can just subtract the boolean property inside the compareFunction. This works because of coercion
true - false === 1 false - true === -1 true - true === 0