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

8

我有一个以表格形式呈现的用户列表。活跃用户应该排在非活跃用户之上。

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

这里有一个使用users数组和sortBy loadsh函数的代码片段:

https://codepen.io/nikolatrajkovicq/pen/pGXdpM?editors=1112

欢迎提出任何建议。


2
你可以创建两个数组,一个是启用的用户,另一个是禁用的用户,然后将禁用的用户连接到启用的用户数组的末尾,这样禁用的用户就会出现在最后面(但不按任何顺序排序)。 - Vencovsky
2个回答

21

您可以像这样使用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中减去布尔属性即可。这是由于强制转换的原因。

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

谢谢你的解决方案和帮助!我还是不太明白这个是如何工作的,能否再给我一些更多的信息? - James Delaney
1
@JamesDelaney,请查看答案中的“sort”链接。它详细解释了“compareFunction”函数。比较函数根据返回值是+ve、-ve还是0将2个项目相对排序。由于“false - true”返回“-1”,反之亦然,我们可以简单地减去正在比较的2个项目的“disabled”属性。 - adiga

4
你可以使用 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",},{disabled:true,email:"hgither@cmregent.com",firstName:"Hrriet",lastName:"Gither",role:"claisHandlerSupervisor",userId:"0VFpxtMWgY1jKDHDLcrWSw1qzx1",},]

let op = userArray.sort(({disabled:A}, {disabled:B})=> A-B)

console.log(op)


1
这个不起作用。结果显示“true -> false -> true”。 - adiga
首先应该呈现活跃用户,最后是非活跃用户。@MaheerAli - Code Maniac
@adiga,你真的检查了代码片段的输出吗? - Code Maniac
1
JavaScript中的排序:返回布尔值不应该足够作为比较函数吗? - adiga
@adiga我正在使用Firefox,它似乎对我来说效果很好。没想到这是依赖于实现的。 - Code Maniac
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接