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

IT技术 javascript arrays reactjs
2021-03-02 09:20:56

我有表中显示的用户列表。活跃用户应该排在非活跃用户之上。

我正在尝试sort使用 lodashsortBy函数进行此操作,但未成功。

这是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

欢迎任何建议。

2个回答

你可以这样使用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. 这是因为强制

true - false === 1
false - true === -1
true - true === 0
@JamesDelaney 请查看sort答案中链接。它详细解释了该compareFunction功能。compare 函数根据返回值是 +ve、-ve 还是 0 对彼此相关的 2 个项目进行排序。 由于false - true返回-1,反之亦然,我们可以简单地减去disabled正在比较的 2 个项目属性
2021-05-01 09:20:56
感谢您的解决方案和帮助!我还是不明白这是如何工作的,如果你能给我更多的信息吗?
2021-05-21 09:20:56

您可以使用排序

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})=> A-B)

console.log(op)

First should be presented Active useres and on the End Inactive users @马希尔阿里
2021-04-27 09:20:56
OP 说我需要首先显示禁用属性 False 的用户,然后显示 true 的用户您的代码true首先向用户显示
2021-05-07 09:20:56
@adiga 你真的检查过片段输出吗?
2021-05-07 09:20:56
这不起作用。结果显示true -> false -> true
2021-05-15 09:20:56