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

时间:2017-05-12 06:40:34

标签: javascript arrays filter compare element

我正在处理这段代码,我需要过滤一个包含多个相同元素的数组,看起来像这样;

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 - 3h 0 m / A250.1 - 6h 0 m

A340.1 - 3h 15 m / A340.1 - 8h 0 m

A240.4 - 4h 0 m / A240.4 - 7h 0 m

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

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个或更多。

任何快速有效的方法吗?

1 个答案:

答案 0 :(得分:1)

尝试使用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;
}, []))