简体   繁体   English

JavaScript-筛选具有相同元素的数组

[英]JavaScript - Filtering array with identical elements

I'm working on this code where I need to filter an array with multiple identical elements, which looks like this; 我正在处理此代码,需要过滤具有多个相同元素的数组,如下所示;

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"]

The identical elements in the uniqueVacant - array are: uniqueVacant数组中的相同元素是:

A250.1 - 3h 0 m / A250.1 - 6h 0 m A250.1-3h 0 m / A250.1-6h 0 m

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

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

I have already filtered out the timestamp from the elements so the only thing needed is to compare the element names; 我已经从元素中滤除了时间戳记,因此唯一需要做的就是比较元素名称。

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

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

The results should look like this, only leaving the first element with the same name and removing the second one which prints out later; 结果应如下所示,只将第一个元素保留相同的名称,并删除第二个元素,稍后再打印出来。

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,

Note that when the timer is up for the elements, they get removed out from the array and after that the second element with the same name should appear back in the array, if there's no more similarities inside the array. 请注意,当元素的计时器用尽时,它们将从数组中移出,然后,如果数组中没有更多相似之处,则具有相同名称的第二个元素应重新出现在数组中。

The similarities also varies from day to day, sometimes it's only 2 similar elements and other days it might be 8 or more. 每天的相似性也有所不同,有时只有2个相似的元素,而其他日子则可能是8个或更多。

Any quick and effective way to do this? 有任何快速有效的方法可以做到这一点吗?

Try with Array#reduce 尝试使用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; }, [])) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM