You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Material UI Autocomplete中实现分组选项先按genre再按title排序?

解决Material UI Autocomplete分组后先按类型再按标题排序的问题

你只需要优化数组的排序逻辑,在**类型(genre)相同的情况下,再对比标题(title)**即可实现需求。具体做法是修改sort的回调函数:

  1. 先对两个元素的genre转小写后做字符串比较
  2. 如果genre的比较结果不为0(即类型不同),直接返回该结果
  3. 如果genre相同,则继续对title转小写后做字符串比较,返回这个结果

修改后的排序代码

const sortedFilms = [...top100Films].sort((a, b) => {
  // 先按genre排序
  const genreDiff = a.genre.toLowerCase().localeCompare(b.genre.toLowerCase());
  if (genreDiff !== 0) {
    return genreDiff;
  }
  // genre相同时按title排序
  return a.title.toLowerCase().localeCompare(b.title.toLowerCase());
});

这里使用localeCompare而非直接用>或<,是因为它能更稳妥地处理字符串排序的各种场景(比如大小写差异、特殊字符等),比手动判断更可靠。同时建议创建新的排序后数组,避免直接修改原数据带来的副作用。

完整组件代码

import * as React from "react";
import TextField from "@mui/material/TextField";
import Autocomplete from "@mui/material/Autocomplete";

export default function Grouped() {
  const sortedFilms = [...top100Films].sort((a, b) => {
    const genreDiff = a.genre.toLowerCase().localeCompare(b.genre.toLowerCase());
    if (genreDiff !== 0) {
      return genreDiff;
    }
    return a.title.toLowerCase().localeCompare(b.title.toLowerCase());
  });

  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" />
      )}
    />
  );
}

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"
  }
];

内容的提问来源于stack exchange,提问作者young_minds1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 08:21:57