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

如何基于目标字符串对对象数组按顺序排序,优先连续长匹配项?

问题描述

给出以下字符串和数组:

const speech = 'marcllh 4th reg gh 4th ethth';

const similarityArray = [
  { split: '4th reg' },
  { split: 'reg gh' },
  { split: 'ethth' },
  { split: 'marcllh' },
  { split: '4th reg gh' },
  { split: '4th ethth' },
];

需要按照原字符串从开头到结尾的顺序对数组排序,同时满足:如果某段拆分文本存在更长的延续版本,需紧跟在对应短版本之后。

期望排序后的数组:

[
  { split: 'marcllh' },
  { split: '4th reg' },
  { split: '4th reg gh' }, // 短版本的延续,紧跟其后
  { split: 'reg gh' },
  { split: '4th ethth' },
  { split: 'ethth' },
]
实现方案

核心思路分两步排序:

  1. 以拆分文本在原字符串中的起始位置为第一优先级,保证整体顺序和原字符串的出现顺序匹配
  2. 对于起始位置相同的项,以字符串长度为第二优先级,短文本在前、长文本在后,确保长版本的延续文本紧跟对应短版本

具体代码实现:

const speech = 'marcllh 4th reg gh 4th ethth';

const similarityArray = [
  { split: '4th reg' },
  { split: 'reg gh' },
  { split: 'ethth' },
  { split: 'marcllh' },
  { split: '4th reg gh' },
  { split: '4th ethth' },
];

// 执行排序
const sortedArray = similarityArray.sort((a, b) => {
  // 获取两个拆分文本在原字符串中的起始索引
  const startIndexA = speech.indexOf(a.split);
  const startIndexB = speech.indexOf(b.split);
  
  // 第一步:按起始位置从小到大排序
  if (startIndexA !== startIndexB) {
    return startIndexA - startIndexB;
  }
  
  // 第二步:起始位置相同时,短文本在前、长文本在后
  return a.split.length - b.split.length;
});

console.log(sortedArray);

代码说明

  • speech.indexOf() 用于获取拆分文本在原字符串中首次出现的起始位置,确保排序基准完全贴合原字符串的顺序
  • 起始位置相同时,短文本在前的规则,刚好满足"长版本延续文本紧跟短版本"的要求
  • 该逻辑直接匹配期望结果,同时覆盖了所有场景的排序需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 21:20:43