小编典典

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

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: "[email protected]",
    firstName: "Harriet",
    lastName: "Gaither",
    role: "claimsHandlerSupervisor",
    userId: "03VFpxtMWgY1jKDHDLcrWSw1qzx1",
  }, 
  {
   disabled: false,  // <===========
   email: "[email protected]",
   firstName: "Harriet",
   lastName: "Gaither",
   role: "claimsHandlerSupervisor",
   userId: "03VFpxtMWgY1jKDHDLcrWSw1qzx1",
 }, 
]

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

任何地方都欢迎。


阅读 400

收藏
2020-07-22

共1个答案

小编典典

您可以这样使用sort

const userArray=[{disabled:true,email:"[email protected]",firstName:"Harriet",lastName:"Gaither",role:"claimsHandlerSupervisor",userId:"03VFpxtMWgY1jKDHDLcrWSw1qzx1",},{disabled:false,email:"[email protected]",firstName:"Harriet",lastName:"Gaither",role:"claimsHandlerSupervisor",userId:"03VFpxtMWgY1jKDHDLcrWSw1qzx1",},]



userArray.sort((a,b) => a.disabled - b.disabled)

console.log(userArray)

您可以只减去中的boolean属性compareFunction。这是因为强制

true - false === 1
false - true === -1
true - true === 0
2020-07-22