[Vuejs]-How to sort bye value and only return items above a certain value?

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.

πŸ‘€adiga

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)
                            )
}
πŸ‘€0xc14m1z

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)
  )
}
πŸ‘€Abdullah Khan

Leave a comment