group通过自动完成物料ui中选项的排序



我正在使用材料ui自动完成并对生成分组自动完成下拉列表作出反应。

以下是数据

let top100Films = [
{ title: "The Shawshank Redemption", genre: "thriller" },
{ title: "The Dark Knight", genre: "super hero" },
{ title: "The Godfather: Part II", genre: "thriller" },
{ title: "12 Angry Men", genre: "war" },
{ title: "Schindler's List", genre: "war" },
{ title: "superman", genre: "super hero" },
{ title: "The Godfather", genre: "thriller" },
{
title: "The Lord of the Rings: The Return of the King",
genre: "adventure"
}
];

我想先按流派排序,然后按标题排序。我能按流派排序,但不能按标题排序以下是代码

import * as React from "react";
import TextField from "@mui/material/TextField";
import Autocomplete from "@mui/material/Autocomplete";
export default function Grouped() {
top100Films = top100Films.sort((a, b) =>
a.genre.toLowerCase() > b.genre.toLowerCase() ? 1 : -1
);
return (
<Autocomplete
id="grouped-demo"
options={top100Films}
groupBy={(option) => option.genre}
getOptionLabel={(option) => option.title}
sx={{ width: 300 }}
renderInput={(params) => (
<TextField {...params} label="With categories" />
)}
/>
);
}
// Top 100 films as rated by IMDb users. http://www.imdb.com/chart/top
let top100Films = [
{ title: "The Shawshank Redemption", genre: "thriller" },
{ title: "The Dark Knight", genre: "super hero" },
{ title: "The Godfather: Part II", genre: "thriller" },
{ title: "12 Angry Men", genre: "war" },
{ title: "Schindler's List", genre: "war" },
{ title: "superman", genre: "super hero" },
{ title: "The Godfather", genre: "thriller" },
{
title: "The Lord of the Rings: The Return of the King",
genre: "adventure"
}
];

下面是代码和盒子的链接

https://codesandbox.io/s/grouped-autocomplete-options-sorting-zrsb34?file=/demo.js:663-1132

我该如何实现。

提前感谢!

尝试像这样更改sort条件:

export default function Grouped() {
const sortedFilms = top100Films.sort((a, b) => {
if (a.genre.toLowerCase() === b.genre.toLowerCase()) {
return a.title.toLowerCase() > b.title.toLowerCase() ? 1 : -1;
}
return a.genre.toLowerCase() > b.genre.toLowerCase() ? 1 : -1;
});
return (
<Autocomplete
id="grouped-demo"
options={sortedFilms}
groupBy={(option) => option.genre}
getOptionLabel={(option) => option.title}
sx={{ width: 300 }}
renderInput={(params) => (
<TextField {...params} label="With categories" />
)}
/>
);
}

链接到沙箱

最新更新