我發現了這個問題的一些答案,但由於某些原因它沒有爲我工作。在JavaScript中使用布爾屬性對一個複雜的對象數組排序
我有一個對象的大型數組需要排序布爾屬性(所有的true
需要首先出現)。最受歡迎的答案是我找到的是:
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
})
不幸的是,這是不工作,我試圖做的是有一些變化,但沒有成功。
這一個替代方案是簡單地做:
myList.sort((x, y) => {return x.sortingAttribute - y.sortingAttribute})
但是它也沒有奏效。我也試圖使用下劃線的sortBy函數,但沒有。
我不認爲這與它有任何關係,但在嘗試排序之前,我在另一個列表上執行.map()
以獲得myList
,因爲它現在是。這是否會成爲問題的原因?除此之外,它非常簡單。
以下是完整的功能:
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的數組吐出來的訂單,我們將有:
假,false,false,true,true
你在做'myList中= myList.sort((X,Y)=> {返回x.sortingAttribute - y.sortingAttribute})'? –
@ Keith that worked!謝謝!如果你想,但它作爲答案,所以我可以標記它。 – theJuls
根據你的結果你可以調用array.reverse(),那麼你的輸出將是真,假,假,假 –