ReactJS:按字母顺序对选项进行排序

时间:2018-11-03 03:59:02

标签: javascript reactjs

我问过this question,但答案只有在所有选项都在几个月后才适合。如果现在,我想按字母顺序对它们进行排序怎么办?

它看起来像这样:

enter image description here

这是我的选择代码:

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

如果这有帮助,我还将介绍this.state.variantsData.subscription_plans返回的内容:

enter image description here

预先感谢您对我的帮助。

1 个答案:

答案 0 :(得分:1)

一种实现方法是使用orderBy提供的名为lodash的函数。

您可以单独使用npm install --save lodash.orderBy安装它,也可以直接安装lodash并导入orderBy函数。

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