最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

SEO心得admin59浏览0评论
本文介绍了如何根据布尔属性对对象数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

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

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

欢迎任何建议.

推荐答案

您可以使用 sort 像这样:

You can use sort like this:

const userArray=[{disabled:true,email:"hgaither@cmregent",firstName:"Harriet",lastName:"Gaither",role:"claimsHandlerSupervisor",userId:"03VFpxtMWgY1jKDHDLcrWSw1qzx1",},{disabled:false,email:"hgaither@cmregent",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
发布评论

评论列表(0)

  1. 暂无评论