0

I have a select and it gets the options from the api, and it looks like this:

enter image description here

I want to sort them in ascending form but I don't know how to do that, here is my code

<select className="form-control form-control-sm" name="subscriptions" onChange={this.changeValues}>
    {
    this.state.variantsData.subscription_plans.map((item, i) => <option key={i} value={item.uuid}>{item.name}</option>)
    }
</select>
eibersji
  • 1,146
  • 3
  • 25
  • 50

1 Answers1

2

You could write a function that sorts your data which you can then render. To optimise it further you can memoize this function

sortData = (array) => {
   return array.sort(function(a, b) {
       a.match(/(\d+) months/i)[1] - b.match(/(\d+) months/i)[1]
   })
}

render() {
   const data = this.sortData(this.state.variantsData.subscription_plan);
   return (
       <select className="form-control form-control-sm" name="subscriptions" onChange={this.changeValues}>
          {this.state.variantsData.subscription_plans.map((item, i) => (
              <option key={i} value={item.uuid}>{item.name}</option>
          ))
          }
       </select>
   ) 
}
Shubham Khatri
  • 246,420
  • 52
  • 367
  • 373