I have been searching for solutions to this issue, but unfortunately nothing seems to be working for me.
My problem involves a large array of objects that I need to sort based on a boolean property (with all the true
values taking precedence). The common solution I have come across is as follows:
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
})
However, despite trying various iterations of this code, it still hasn't produced the desired result.
Another approach suggested is simply using:
myList.sort((x, y) => {return x.sortingAttribute - y.sortingAttribute})
Yet, even this method has not proven effective. I also experimented with underscore's sortBy function, without success.
While it may not seem relevant, before attempting to sort the array, I perform a .map()
on another list to obtain the current structure of myList
. Could this somehow be causing the issue? Apart from that, everything appears to be straightforward.
Below is the complete function:
getMyList (basicArray) {
let myList = basicArray.map((arr, key) => {
const sortingAttribute = key > 2 // just used for the example
// in reality, there would be a more random arrangement of true and false values
// other operations
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)
}
Currently, the output reflects the order generated by the .map()
function. For a list of size 5, the sequence would be:
false, false, false, true, true