[英]VueJS sort/order an array of objects by a specific property
I have an array of contact objects that all of an isPrimary
property. 我有所有
isPrimary
属性的联系人对象数组。 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.
我正在使用VueJS并计划在列表组件中创建它。 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.
我知道我可以创建一个计算属性,但是当它不真正比较a和b时,只是不确定如何重新排序,而只是想对其重新排序,因此不确定如何使用sort。 Here's a rough start:
这是一个粗略的开始:
sortedContacts () {
return this.contacts.sort((a, b) => { // what to do here? })
}
Any assistance would be hugely appreciated! 任何帮助将不胜感激!
Use sort
and Boolean to number type coercion like so: 使用
sort
和Boolean对强制类型进行编号,如下所示:
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. 通过比较
true
和false
的数字表示(分别为1
和0
,并基于sort
的回调的返回值,它返回一个数字,该数字确定每个项目也应移动的位置。
this.contacts.sort((a, b) => { a.isPrimary ? -1 : 1 })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.