javascript - Javascript数组分组和过滤
问题描述
我有一个 Javascript 数组,如下所示
const array = [
"AB01-E-1000-0"
"AB01-E-1050-0"
"AB01-E-1100-0"
"AB01-T-1050-0"
"AB02-W-1000-0"
"AB02-W-1050-0"
"AB02-W-1100-0"
"AB02-W-1150-0"
...
]
每个字符串包含 2 个部分 - (例如第一部分AB01-E
和第二部分1000-0
)。我想按第一部分对项目进行分组(例如AB01-E-1000-0
,AB01-E-1050-0
并被AB01-E-1100-0
视为一个组)。对于每一组,我想在第二部分(例如AB01-E-1000-0
)中获得最小的数字。
处理后的数组应如下所示:
[
"AB01-E-1000-0"
"AB01-T-1050-0"
"AB02-W-1000-0"
...
]
提前致谢
解决方案
const array = [ "AB01-E-1000-0", "AB01-E-1050-0", "AB01-E-1100-0", "AB01-T-1050-0", "AB02-W-1000-0", "AB02-W-1050-0", "AB02-W-1100-0", "AB02-W-1150-0" ];
const getSectionNumericValue = (section='') => +section.replace('-', '');
const res = [...
// get map of first two as key and second two as value
array.reduce((sectionsMap, item) => {
const firstSection = item.split('-', 2).join('-');
const secondSection = item.split('-').slice(-2).join('-');
const currentMin = sectionsMap.get(firstSection);
if(!currentMin ||
getSectionNumericValue(currentMin) > getSectionNumericValue(secondSection)) {
sectionsMap.set(firstSection, secondSection);
}
return sectionsMap;
}, new Map())
// convert to array of pairs
.entries()]
// merge two parts for each record
.map(pair => pair.join('-'));
console.log(res);
推荐阅读
- java - Spring MVC 无法加载 .jsp 文件但返回 404 错误
- python - 如何在 python 中连接到 teiid VDB
- nginx - 带有 Stream 块的 Nginx 反向代理未连接到服务器
- python-3.x - 如何(成功)在 spyder(anaconda)上的 Python 3.6 64 位和 32 位之间切换
- java - Gradle for Java 项目中的 ClassNotFound 错误
- java - 转向 jpql 查询
- sockets - 当客户端和服务器在不同的机器上时,getsockname() 不会返回正确的地址
- command - 我添加了一个东西,如果有人离开,我的机器人会 dm,但现在我只是不断收到错误消息
- html - href=“tel:” tel 中间有 +
- php - Laravel 抛出一个自定义的 ValidationException