0

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!

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.