【问题标题】:Best way to remove duplicate sentences from an array of sentences based on their characters, whitespaces inconsequential根据字符的字符从句子数组中删除重复句子的最佳方法,空格无关紧要
【发布时间】:2021-12-03 16:50:08
【问题描述】:

假设我们有一个这样的数组

const array = ['bic ycle drive', 'bici ycl frei', 'bicyc le dri ve', 'manace', 'bicycle drive', 'bicycle drive']

我希望它返回['bic ycle drive', 'bici ycl frei', 'manace'],因为bic ycle drive, bicyc le dri ve, bicycle drive, bicycle drive 是同一个句子,不同地方有空格。

总结:只返回唯一值,空格不重要。

Ps:我们可以选择任何重复的。

谢谢。

【问题讨论】:

  • 为什么不直接返回不带空格的单词?
  • “实现...的最佳方式” 征求题外话

标签: javascript arrays duplicates


【解决方案1】:

从 ES6 开始,使用 Set 创建唯一值数组很容易,但在这种情况下,您需要转换字符串(删除空格)以查找重复项,但仍保留原始字符串,以便您可以返回它们。您可以通过创建一个 Map 来做到这一点,其中“没有空格的字符串”作为键,原始字符串作为值。由于 Map 的键是唯一的。

使用Array.map() 创建一个映射以生成[string without spaces, string] 的数组。然后将 Map.values() 迭代器转换回数组。这将返回每一系列重复项中的最后一项。

const array = ['bic ycle drive', 'bici ycl frei', 'bicyc le dri ve', 'manace', 'bicycle drive', 'bicycle drive']

const result = [...new Map(
  array.map(str => [str.replace(/\s+/g, ''), str])
).values()]

console.log(result)

如果您想要一系列重复项中的第一项,可以使用Array.reduce() 创建 Map,并且仅在它们不存在时分配键:

const array = ['bic ycle drive', 'bici ycl frei', 'bicyc le dri ve', 'manace', 'bicycle drive', 'bicycle drive']

const result = [...array.reduce((acc, str) => {
  const key = str.replace(/\s+/g, '')
  
  return acc.has(key) ? acc : acc.set(key, str)
}, new Map()).values()]

console.log(result)

【讨论】:

  • 很聪明
  • 这真的很酷。谢谢。
  • 不客气 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-11
  • 1970-01-01
  • 2016-11-17
  • 2013-09-18
  • 1970-01-01
相关资源
最近更新 更多