如何根据布尔属性对对象数组进行排序? [英] How to sort array of objects based on a boolean property?

查看:34
本文介绍了如何根据布尔属性对对象数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have list of users presented in table. Active users should be sorted above the inactive users.

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

I am trying to make this sort using lodash sortBy function, but unsuccessfully.

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

here is code pen with code with users array and sortBy loadsh function: https://codepen.io/nikolatrajkovicq/pen/pGXdpM?editors=1112

欢迎任何建议.

推荐答案

您可以使用 sort 像这样:

You can use sort like this:

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 中的布尔属性.这是因为强制

You can just subtract the boolean property inside the compareFunction. This works because of coercion

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

这篇关于如何根据布尔属性对对象数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆