JavaScript - 过滤具有相同元素的数组

JavaScript - Filtering array with identical elements

我正在编写这段代码,我需要在其中过滤具有多个相同元素的数组,如下所示;

vacant = [
"A510.4 - 0h 45 m",
"A520.6 - 3h 0 m",
"A250.1 - 3h 0 m",
"A340.1 - 3h 15 m",
"A320.2 - 3h 0 m",
"A240.4 - 4h 0 m",
"A210.3 - 4h 0 m",
"A520.5 - 5h 0 m",
"A250.1 - 6h 0 m",
"A240.4 - 7h 0 m",
"A320.6 - 8h 0 m",
"A340.1 - 8h 0 m"]

uniqueVacant - 数组中相同的元素是:

A250.1 - 3 小时 0 米 / A250.1 - 6 小时 0 米

A340.1 - 3 小时 15 米 / A340.1 - 8 小时 0 米

A240.4 - 4 小时 0 米 / A240.4 - 7 小时 0 米

我已经从元素中过滤掉了时间戳,所以唯一需要做的就是比较元素名称;

function getName(str) {
  return str.substring(0, str.indexOf('-'));
}

var uniqueVacant = [];
vacant.forEach(function (vacantStr) {
  uniqueVacant.push(getName(vacantStr))
});

结果应该是这样的,只保留同名的第一个元素并删除稍后打印的第二个元素;

uniqueVacant = [
"A510.4 - 0h 45 m",
"A520.6 - 3h 0 m",
"A250.1 - 3h 0 m",
"A340.1 - 3h 15 m",
"A320.2 - 3h 0 m",
"A240.4 - 4h 0 m",
"A210.3 - 4h 0 m",
"A520.5 - 5h 0 m",
"A320.6 - 8h 0 m"]

// Removed A250.1 - 6h 0 m, A340.1 - 8h 0 m, A240.4 - 7h 0 m,

请注意,当元素的计时器到时,它们会从数组中删除,之后如果数组中没有更多相似之处,则具有相同名称的第二个元素应该出现在数组中。

相似度也每天都在变化,有时只有 2 个相似元素,而其他日子可能有 8 个或更多。

有什么快速有效的方法吗?

试试 Array#reduce

var vacant = [
  "A510.4 - 0h 45 m",
  "A520.6 - 3h 0 m",
  "A250.1 - 3h 0 m",
  "A340.1 - 3h 15 m",
  "A320.2 - 3h 0 m",
  "A240.4 - 4h 0 m",
  "A210.3 - 4h 0 m",
  "A520.5 - 5h 0 m",
  "A250.1 - 6h 0 m",
  "A240.4 - 7h 0 m",
  "A320.6 - 8h 0 m",
  "A340.1 - 8h 0 m"
]

console.log(vacant.reduce((a, b) => {
  var k = a.map(a => a.split('-')[0])
  if (!k.includes(b.split("-")[0])) {
    a.push(b)
    k.push(b.split("-")[0])
  }
  return a;
}, []))