2

I have asked this question but the answer fits only if the options are all in months. What if now, I want to sort them alphabetically?

It looks like this:

enter image description here

and here is my code for the select:

<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>

if this would help, I'll also include what this.state.variantsData.subscription_plans returns:

enter image description here

thank you in advance for helping me.

eibersji
  • 1,218
  • 4
  • 29
  • 52
  • You can answer of that question and update sort function to sort by [alphabetical order](https://stackoverflow.com/questions/6712034/sort-array-by-firstname-alphabetically-in-javascript) – Tu Tran Nov 03 '18 at 04:24

1 Answers1

2

One way to do that is by using a function called orderBy provided by lodash.

You can install it individually with npm install --save lodash.orderBy or just install lodash itself and import the orderBy function.

const orderPlans = plans => (
  _.orderBy(plans, item => (
    // get each item, extract the number from `name` and
    // parse it to int, so that the order function works
    // correctly. otherwise, we would have something like
    // 1 month, 10 months, 11 months, 2 months
    parseInt(
      item.name.replace(/\D+/gi, ''))
    )
  )
);

const App = () => {
  // sample of your api response...
  const plans = [
    { uuid: '1', name: '3 months'}, 
    { uuid: '2', name: '6 months'}, 
    { uuid: '3', name: '1 month'},
    { uuid: '4', name: '2 months'},
    { uuid: '5', name: '14 months'},
    { uuid: '6', name: '10 months'}
  ];
  
  return (
    <select 
      className="form-control form-control-sm"        
      name="subscriptions" 
    > 
      {orderPlans(plans).map(item => (
        <option key={item.uuid} value={item.uuid}>
          {item.name}
        </option>
      ))}
    </select>
  );
}

ReactDOM.render(<App/>, document.querySelector('main'));
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<main />
Julio Betta
  • 2,275
  • 1
  • 25
  • 25