javascript - 如何根据 bool 属性对对象数组进行排序?

标签 javascript arrays reactjs

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

我正在尝试使用 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",
 }, 
]

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

欢迎任何建议。

最佳答案

您可以使用 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 中的 bool 属性。这是因为强制

true - false === 1
false - true === -1
true - true === 0

关于javascript - 如何根据 bool 属性对对象数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54826537/

相关文章:

php - 添加好友按钮/链接

java - StringBuffer char[] 似乎超出堆转储中的范围

javascript - 在故事书中用 react native 矢量图标 react native 网络问题

javascript - 有什么办法可以缩短这段代码吗?

Javascript 动态数组不工作

javascript - Reactjs。无法将变量传递给类

javascript - Google Chrome 扩展对于任何 getElement 返回未定义

javascript - 我怎样才能简化这个 jquery?

javascript - 使用 Knockjs 时未触发单击事件

javascript - 将 HTML-Select 附加到输入并在用户单击“保存”按钮后存储它们的值