Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sort drop-down menu items alphabetically?

Is there any way to display options in an alphabetical order in the drop-down menu of Material-UI?

I know that arrays can be sorted simply using arr.sort(). However, if I do const options = [...].sort(), then I still see unsorted values in the drop-down menu.

const options = [
  {label:"B",value:8033.86},
  {label:"A",value:483.93},
  {label:"Z",value:1246.3},
  {label:"C",value:145.0},
  {label:"E",value:244.5}
]

<Grid item xs={true}>
  <FormControl
      className={this.props.styles.formControl}
      margin="normal">
      <InputLabel shrink htmlFor="distanceTarget-label-placeholder">
          Target:
      </InputLabel>
      <Select
        onChange={(event) => this.props.handleChange("distanceTarget", event)}
        value={this.props.state.distanceTarget}
        input={<Input name="distanceTarget" id="distanceTarget-label-placeholder" />}
        displayEmpty="true"
        name="distanceTarget"
      >
      {options && options.length && options.map((option, i) => {
          return <MenuItem value={option.value} key={i}>{option.label}</MenuItem>
      })}
      </Select>
  </FormControl>
</Grid>
like image 538
ScalaBoy Avatar asked Jan 21 '26 10:01

ScalaBoy


2 Answers

here a simple way to sort the array of objects and you can read the documentation

const options = [
  {label:"B",value:8033.86},
  {label:"A",value:483.93},
  {label:"Z",value:1246.3},
  {label:"C",value:145.0},
  {label:"E",value:244.5}
]

console.log(options.sort((a, b) => (a.label > b.label) ? 1 : -1))
like image 186
Nemer Avatar answered Jan 24 '26 00:01

Nemer


Material-UI is about styles, not logic. First of all, you need to sort your options.

    for (const item in options) {
     console.log(options[item].label)
    }

Its first steps. The second you should try yourself.

like image 36
Hubi Avatar answered Jan 23 '26 23:01

Hubi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!