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

如何在React中将单个动态列表按首字母拆分为多个独立列表

解决方案

先对原始列表按条目标题的首字母做分组处理,再遍历分组后的结果渲染对应<ul>结构即可,参考代码如下:

1. 数据分组逻辑

const groupedList = list.reduce((result, currentItem) => {
  // 取标题首字符,统一转为大写,不需要区分大小写可删除toUpperCase()
  // 兼容空标题场景,空标题会被归类到#分组下,不需要可以去掉兼容逻辑
  const firstLetter = currentItem.title?.[0]?.toUpperCase() || '#'
  if (!result[firstLetter]) {
    result[firstLetter] = []
  }
  result[firstLetter].push(currentItem)
  return result
}, {})

2. 组件渲染逻辑

替换你原来的渲染代码为以下内容即可:

{/* 如需按首字母排序,可在entries后加.sort((a,b) => a[0].localeCompare(b[0])) */}
{Object.entries(groupedList).map(([letter, itemList]) => (
  <ul key={letter}>
    {itemList.map((item) => (
      <li key={item.id ?? item.title}>
        {item.title}
      </li>
    ))}
  </ul>
))}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 20:54:02