如何根据布尔属性对对象数组进行排序?

Jam*_*ney 3 javascript arrays reactjs

我有表中显示的用户列表.活动用户应排在非活动用户之上.

我试图sort使用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",
 }, 
]
Run Code Online (Sandbox Code Playgroud)

这里是带有用户数组和sortBy loadsh函数的代码的代码笔:https://codepen.io/nikolatrajkovicq/pen/pGXdpM?editors = 1112

欢迎任何adivce.

adi*_*iga 7

你可以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)
Run Code Online (Sandbox Code Playgroud)

这是因为

true - false === 1
false - true === -1
true - true === 0
Run Code Online (Sandbox Code Playgroud)