对值相同的重复元素编号:《指环王》JSON电影标题编号替代方案求助
《指环王》电影标题编号替代实现方案
你当前的写法需要为每部电影单独编写if判断分支,硬编码程度高,扩展和维护都比较麻烦,以下是几种更灵活的实现方案:
- 方案1:映射表匹配法(最常用,适合固定系列场景)
提前把标题和对应序号的映射关系定义好,无需编写多分支判断,后续新增系列内容只需修改映射表即可:
// 定义标题与序号的映射关系,可按需扩展 const LOTRTitleSerialMap = { "The Fellowship of the Ring": 1, "The Two Towers": 2, "The Return of the King": 3 } const newArray = arr.map(element => { const originalTitle = element[0] const serial = LOTRTitleSerialMap[originalTitle] // 匹配到对应系列标题就加编号,未匹配到则保留原内容 return serial ? `${serial}. ${originalTitle}` : originalTitle })
- 方案2:自动计数法(适合同标题连续分组的数组结构)
如果你的JSON数组是按照系列顺序排列,相同电影的条目连续存放,完全不需要硬编码标题内容,可以自动识别新的标题并累加序号:
let currentSerial = 1 let lastProcessedTitle = arr[0]?.[0] ?? '' const newArray = [] arr.forEach(element => { const currentTitle = element[0] // 遇到新的标题时序号自增 if(currentTitle !== lastProcessedTitle) { currentSerial++ lastProcessedTitle = currentTitle } newArray.push(`${currentSerial}. ${currentTitle}`) })
- 方案3:原地修改法(适合不需要保留原数组内容的场景)
如果你不需要保留原始的标题内容,可以直接修改原数组的对象属性,节省内存开销:
const LOTRTitleSerialMap = { "The Fellowship of the Ring": 1, "The Two Towers": 2, "The Return of the King": 3 } arr.forEach(element => { const originalTitle = element[0] if(LOTRTitleSerialMap[originalTitle]) { element[0] = `${LOTRTitleSerialMap[originalTitle]}. ${originalTitle}` } })
内容的提问来源于stack exchange,提问作者AAH
相关产品推荐
相关产品推荐

