Matt Larsuma
Matt Larsuma

Reputation: 1519

VueJS sort/order an array of objects by a specific property

I have an array of contact objects that all of an isPrimary property. Only one of them should be true, but regardless I would like to sort any primary contacts to the top of the array. I'm using VueJS and plan to do this on created in a list component. I know I can create a computed property, but not sure how to use sort when it's not really comparing a and b, but just looking to re-order any that are primary. Here's a rough start:

sortedContacts () {
  return this.contacts.sort((a, b) => { // what to do here? })
}

Any assistance would be hugely appreciated!

Upvotes: 0

Views: 687

Answers (2)

Jack Bashford
Jack Bashford

Reputation: 44107

Use sort and Boolean to number type coercion like so:

return this.contacts.sort(({ isPrimary: a }, { isPrimary: b }) => b - a);

This works by comparing the numeric representations of true and false, which are 1 and 0 respectively, and based upon the return value of sort's callback, it returns a number which determines the place each item should be moved too.

Upvotes: 2

Stephen Thomas
Stephen Thomas

Reputation: 14053

this.contacts.sort((a, b) => { a.isPrimary ? -1 : 1 })

Upvotes: 1

Related Questions