[英]How to sort array of objects based on a boolean property?
I have list of users presented in table. 我有表中显示的用户列表。 Active users should be sorted above the inactive users.
活动用户应排在非活动用户之上。
I am trying to make this sort
using lodash sortBy
function, but unsuccessfully. 我试图使用lodash
sortBy
函数进行此类sort
,但未成功。
Here is how userArray
looks: 以下是
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",
},
]
here is code pen with code with users array and sortBy loadsh function: https://codepen.io/nikolatrajkovicq/pen/pGXdpM?editors=1112 这里是带有用户数组和sortBy loadsh函数的代码的代码笔: https ://codepen.io/nikolatrajkovicq/pen/pGXdpM?editors = 1112
Any adivce is welcome. 欢迎任何adivce。
You can use sort
like this: 你可以使用这样的
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)
You can just subtract the boolean property inside the compareFunction
. 你可以在
compareFunction
减去boolean属性。 This works because of coercion 这是因为强制而起作用
true - false === 1
false - true === -1
true - true === 0
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",},{disabled:true,email:"hgither@cmregent.com",firstName:"Hrriet",lastName:"Gither",role:"claisHandlerSupervisor",userId:"0VFpxtMWgY1jKDHDLcrWSw1qzx1",},] let op = userArray.sort(({disabled:A}, {disabled:B})=> AB) console.log(op)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.