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

如何匹配两个数组并支持备选拼写匹配?

解决方案

要实现同时匹配流派名称和备选拼写,并返回对应ID数组,你可以通过以下两种方式实现:

方法一:直接遍历匹配

这种方式适合数据量较小的场景,逻辑直观:

const genres = [
    { id: 20, name: 'Hip-Hop', alt_spelling: [ 'Hip Hop', 'HipHop' ] },
    { id: 21, name: 'House', alt_spelling: [ 'Deep House', 'Acid' ]},
    { id: 22, name: 'Alternative', alt_spelling: [] },
    { id: 23, name: 'Dance', alt_spelling: ["Techno"] }
];
const tags = ["Alternative", "Deep House", "Techno"];

const matchedIds = tags
  // 统一转为小写,消除大小写差异
  .map(tag => tag.toLowerCase())
  // 查找每个tag对应的流派
  .map(tagLower => genres.find(genre => 
    genre.name.toLowerCase() === tagLower || 
    genre.alt_spelling.some(alt => alt.toLowerCase() === tagLower)
  ))
  // 过滤未匹配到的项
  .filter(Boolean)
  // 提取ID并按升序排序
  .map(genre => genre.id)
  .sort((a, b) => a - b);

console.log(matchedIds); // 输出 [21, 22, 23]

方法二:构建映射表优化性能

如果流派数据量较大,先构建「拼写-ID」映射表可以大幅提升查找效率:

const genres = [
    { id: 20, name: 'Hip-Hop', alt_spelling: [ 'Hip Hop', 'HipHop' ] },
    { id: 21, name: 'House', alt_spelling: [ 'Deep House', 'Acid' ]},
    { id: 22, name: 'Alternative', alt_spelling: [] },
    { id: 23, name: 'Dance', alt_spelling: ["Techno"] }
];
const tags = ["Alternative", "Deep House", "Techno"];

// 构建所有拼写(名称+备选)到ID的映射
const spellingMap = new Map();
genres.forEach(genre => {
  spellingMap.set(genre.name.toLowerCase(), genre.id);
  genre.alt_spelling.forEach(alt => spellingMap.set(alt.toLowerCase(), genre.id));
});

// 快速查找匹配的ID
const matchedIds = tags
  .map(tag => spellingMap.get(tag.toLowerCase()))
  .filter(Boolean)
  .sort((a, b) => a - b);

console.log(matchedIds); // 输出 [21, 22, 23]

核心逻辑说明

  • 统一转为小写:避免大小写不一致导致的匹配失败(比如"Deep House"和"deep house"视为同一内容)
  • 匹配规则:每个tag要么匹配流派的name,要么匹配alt_spelling数组中的任意一项
  • 排序:最后通过sort()将ID按升序排列,得到你需要的[21, 22, 23]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 15:15:38