如何根据布尔属性对对象数组进行排序? [英] How to sort array of objects based on a boolean property?
本文介绍了如何根据布尔属性对对象数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在表中列出了用户列表. 活动用户应在非活动用户上方排序.
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
任何人都欢迎.
推荐答案
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屋!
查看全文