0

Beginner at JavaScript and ReactJs. I'm trying to sort this list while displaying options on the front end.

  <Select
                value={Reactivity}
                options={[
                  { label: "Chicken", value: "Chicken" },              
                  { label: "Rat", value: "Rat" },
                  { label: "Dog", value:"Dog"},
                  { label: "Pig", value:"Pig"},
                ]}
                placeholder="Reactivity"
                onChange={(v) => {
                  setReactivity(v.map((vv) => vv));
                }}
                isClearable
                isMulti
    />

// Code to display and choose options

mstarluk
  • 35
  • 1
  • 6
  • 2
    btw if you are hardcoding it why dont you write it sorted anyway. if its from a db or something try https://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value – cmgchess Jul 18 '22 at 07:08
  • 1
    Does this answer your question? [Sort array of objects by string property value](https://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value) – pilchard Jul 18 '22 at 07:16
  • Yes, they're coming from a DB but I'm entering the options manually which is not optimal. – mstarluk Jul 18 '22 at 07:31

2 Answers2

2

You can use Array.sort

<Select
    value={Reactivity}
    options={[
        { label: "Chicken", value: "Chicken" },              
        { label: "Rat", value: "Rat" },
        { label: "Dog", value:"Dog"},
        { label: "Pig", value:"Pig"},
    ].sort((a, b) => a.label.localeCompare(b.label))}
    placeholder="Reactivity"
    onChange={(v) => {
        setReactivity(v.map((vv) => vv));
    }}
    isClearable
    isMulti
/>
Abito Prakash
  • 4,368
  • 2
  • 13
  • 26
0

You can read more about sort() and localeCompare().

You can do something like this :

<Select
    value={Reactivity}

    options={() => [
        { label: "Chicken", value: "Chicken" },              
        { label: "Rat", value: "Rat" },
        { label: "Dog", value:"Dog"},
        { label: "Pig", value:"Pig"},
       ].sort((a, b) => a.label.localeCompare(b.label))
    }
    placeholder="Reactivity"

    onChange={(v) => {
        setReactivity(v.map((vv) => vv));
    }}
    isClearable
    isMulti
/>
Hritik Sharma
  • 1,756
  • 7
  • 24