【问题标题】:How to sort array of objects based on a boolean property?如何根据布尔属性对对象数组进行排序?
【发布时间】:2023-04-05 22:08:01
【问题描述】:

我在表格中列出了用户列表。 活跃用户应该排在非活跃用户之上。

我正在尝试使用 lodash sortBy 函数制作这个 sort,但没有成功。

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 个数组,包含启用和禁用用户,而不是在启用结束时连接禁用,这将使禁用用户出现在最后(但不按任何顺序排序)

标签: javascript arrays reactjs


【解决方案1】:

你可以像这样使用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 ,反之亦然,我们可以简单地减去 2 个项目的 disabled 属性比较
【解决方案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",},{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)

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-03
  • 1970-01-01
  • 2019-12-19
  • 1970-01-01
  • 2017-02-23
相关资源
最近更新 更多