在JavaScript中使用布尔值属性对复杂的对象数组进行排序 [英] Sorting a complex array of objects using a boolean attribute in JavaScript
问题描述
我找到了这个问题的一些答案,但是由于某种原因,它对我没有用.
I have found a few answers to this question, but for some reason it hasn't worked for me.
我有一大堆需要按布尔属性排序的对象(所有 true
的对象都必须首先出现).我找到的最受欢迎的答案是:
I have a large array of objects that needs to be sorted by a boolean property (all the ones that are true
need to appear first). The most popular answer I find is:
let myList = [
{
thing: <div>Something</div>,
sortingAttribute: false
},
{
thing: <div>Something else</div>,
sortingAttribute: true
},
{
thing: <div>Whatever</div>,
sortingAttribute: true
}
.
.
.
]
myList.sort((x, y) => {
return (x.sortingAttribute === y.sortingAttribute) ? 0 : x ? -1 : 1
})
不幸的是,这不起作用,我尝试对其进行一些修改,但无济于事.
Unfortunately this is not working and I have attempted to make a few variations of it, to no avail.
一种替代方法是:
myList.sort((x, y) => {return x.sortingAttribute - y.sortingAttribute})
但是它也没有起作用.我也尝试使用下划线的sortBy函数,但是什么也没有.
However it also hasn't worked. I also attempted to use underscore's sortBy function, but nothing.
我认为这与它无关,但是在尝试进行排序之前,我在另一个列表上执行了一个 .map()
以获取 myList
作为就是现在.这会是问题的原因吗?除此之外,它非常简单.
I wouldn't think this has anything to do with it, but prior to attempting to sort I do a .map()
on another list to get myList
as it is now. Would this somehow be the cause of the problem? Other than that it is pretty straight forward.
以下是全部功能:
getMyList (basicArray) {
let myList = basicArray.map((arr, key) => {
const sortingAttribute = key > 2 // just used for the example
// the real code would obviously generate a more random order of trues and falses
// do other stuff
return {
thing: (<div key={key}>{stuff}</div>),
sortingAttribute: sortingAttribute
}
})
myList.sort((x, y) => {
return (x.isQualified === y.isQualified) ? 0 : x ? -1 : 1
})
console.log('myList SORTED', myList)
}
当前可以准确显示从 .map()
发出的订单因此,对于大小为5的数组,我们将有:
Currently that displays exactly the order that was spat out from the .map()
So for an array of size 5, we would have:
false,false,false,true,true
false, false, false, true, true
推荐答案
您可以采用布尔值 b
和值 a
的差值,因为 true
变为值 1
和 false
0
,并使用减号运算符隐式转换为数字.
You could take the delta of boolean value b
and value a
, because true
becomes the value 1
and false
0
with an implicit casting to number with the minus operator.
var array = [false, true, false, false, true, true, false, true];
array.sort((a, b) => b - a);
console.log(array);
这篇关于在JavaScript中使用布尔值属性对复杂的对象数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!