theJuls
theJuls

Reputation: 7470

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.

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.

An alternative to this is simply doing:

myList.sort((x, y) => {return x.sortingAttribute - y.sortingAttribute})

However it also hasn't worked. I also attempted to use underscore's sortBy function, but nothing.

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.

Here is the full function:

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)
  }

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

Upvotes: 1

Views: 769

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386680

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);

Upvotes: 2

Related Questions