1π
sort
function returns an array of the same length as the original array. So, you canβt do this in a single call. You need to filter
like this before calling sort
.
sortedObject() {
return this.arrayOfObjects
.filter(a => this.formatValue(a) > 0.7)
.sort((a, b) => this.formatValue(b) - this.formatValue(a))
}
If formatValue()
is an expensive operation and you want to call it only once per object, then you can map
it to a new Array before doing filter
. But, this returns an array of objects with an additional property 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)
}
Another option is to use a getter
property inside each object and call the formatValue()
function in it.
2π
Than itβs not just sorting, you need to first filter items with < 0.7, then sort the rest:
I would first map only the computed values, then filter them and then sort them:
sortedObject(){
return this.arrayOfObjects.map(a => this.formatValue(a))
.filter(a => a > 0.7)
.sort((a, b) => b - a)
}
Edit
sortedObject(){
return this.arrayOfObjects.filter(a => this.formatValue(a) > 0.7)
.sort(
(a, b) =>
this.formatValue(b) - this.formatValue(a)
)
}
1π
user filter pipe here
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)
)
}