【问题标题】:Sort list of strings and give preference to string more closer to start index对字符串列表进行排序并优先选择更接近起始索引的字符串
【发布时间】:2019-12-15 17:57:57
【问题描述】:

创建一个在您键入时显示结果的网络组件。目前我有如下字符串列表:

[
  'Aaeaca Bi',
  'Aegaca Bd',
  'Biah gi',
  'dBciag ch',
  'Ghiad dl',
]

当用户输入“B”时进行搜索,目前我得到的结果是:

'Aaeaca Bi',
'Aegaca Bd',
'Biah gi',
'dBciag ch'

但我想要:

'Biah gi',
'dBciag ch',
'Aegaca Bd',
'Aaeaca Bi',

我想获得搜索结果,优先选择更接近起始索引的结果。

我该如何解决这个问题?

【问题讨论】:

  • 你按什么排序列表?你试过什么?你有没有想过每次输入新字符时都创建一个新列表并对其进行排序lexicographically
  • 您只需按每个结果字符串中“B”的索引对结果进行排序。

标签: javascript string sorting


【解决方案1】:

按字符串的indexOf的差异排序,在数组项中查找:

const arr = [
  'Aaeaca Bi',
  'Aegaca Bd',
  'Biah gi',
  'dBciag ch',
  'Ghiad dl',
  'xxxx',
];
const strToFind = 'B';
const result = arr
  .filter(str => str.includes(strToFind))
  .sort((a, b) => a.indexOf(strToFind) - b.indexOf(strToFind))
console.log(result);

可能在这种情况下并不重要(对于给定的一段代码,性能很少有影响),但您可以通过使用将计算复杂度降低到 O(n) 而不是 O(n log n)计数排序而不是内置的.sort

如果你想让搜索不区分大小写,把初始数组变成一个既包含小写版本又包含原始版本的数组,然后通过检查小写版本进行操作,最后映射到原始版本:

const arr = [
  'Aaeaca Bi',
  'Aegaca Bd',
  'Biah gi',
  'dBciag ch',
  'Ghiad dl',
  'xxxx',
  'aabaa'
];
const casedArr = arr.map(str => [str.toLowerCase(), str]);
const strToFind = 'B'.toLowerCase();
const result = casedArr
  .filter(([str]) => str.includes(strToFind))
  .sort((a, b) => a[0].indexOf(strToFind) - b[0].indexOf(strToFind))
  .map(([, origCasedStr]) => origCasedStr);
console.log(result);

【讨论】:

  • filter 创建一个新数组。所以不需要slice
  • 哎呀,你是对的。我最初使用sort,所以我确定slice,然后意识到我也需要filter,但没有删除slice
  • @CertainPerformance 如果你让它不区分大小写会很好,因为 OP 正在谈论搜索。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-28
  • 1970-01-01
  • 2021-06-10
  • 2021-03-17
  • 1970-01-01
  • 2015-03-26
相关资源
最近更新 更多