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
CodePudding user response:
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
/>
CodePudding user response:
You can sort by the Array
method sort()
, and to sort alphabetic, you need to use string localeCompare()
method
<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
/>
CodePudding user response:
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
/>