我想对一个对象数组进行排序,它们在sort方法中的项通过一个函数返回一个值,然后返回值大于某个特定数字的对象项。
我试过了:
sortedObject(){
return this.arrayOfObjects.sort((a, b) =>
(this.formatValue(b) > 0.7) - (this.formatValue(a) > 0.7)
)
}
this.formatValue
从对象属性中获取一个项,并通过一系列计算返回一个介于0和1之间的值。我希望排序只返回值大于0.7的项,并将它们放入sortedObject
计算属性中。值小于0.7的项将不会包含在sortedObject
中。
发布于 2019-01-15 13:08:15
sort
函数返回与原始数组长度相同的数组。因此,您不能在单个调用中完成此操作。在调用sort
之前,您需要像这样执行filter
。
sortedObject() {
return this.arrayOfObjects
.filter(a => this.formatValue(a) > 0.7)
.sort((a, b) => this.formatValue(b) - this.formatValue(a))
}
如果formatValue()
是一个开销很大的操作,并且您希望每个对象只调用一次,那么您可以在执行filter
之前将其map
到新的数组中。但是,这将返回一个具有附加属性formatValue
的对象数组
sortedObject() {
return this.arrayOfObjects
.map(a => ({ formatValue: this.formatValue(a), ...a}))
.filter(a => a.formatValue > 0.7)
.sort((a, b) => b.formatValue - a.formatValue)
}
另一种选择是在每个对象中使用getter
属性,并在其中调用formatValue()
函数。
发布于 2019-01-15 12:09:02
那么它不仅仅是排序,你需要首先筛选< 0.7的项目,然后对其余的项目进行排序:
我首先只映射计算值,然后过滤它们,然后对它们进行排序:
sortedObject(){
return this.arrayOfObjects.map(a => this.formatValue(a))
.filter(a => a > 0.7)
.sort((a, b) => b - a)
}
编辑
sortedObject(){
return this.arrayOfObjects.filter(a => this.formatValue(a) > 0.7)
.sort(
(a, b) =>
this.formatValue(b) - this.formatValue(a)
)
}
发布于 2019-01-15 12:09:54
用户筛选器管道此处为https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
sortedObject(){
return this.arrayOfObjects
..filter(a=> a > 0.7);
.sort((a, b) =>
(this.formatValue(b) > 0.7) - (this.formatValue(a) > 0.7)
)
}
https://stackoverflow.com/questions/54198487
复制