首页 > 解决方案 > 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-0AB01-E-1050-0并被AB01-E-1100-0视为一个组)。对于每一组,我想在第二部分(例如AB01-E-1000-0)中获得最小的数字。

处理后的数组应如下所示:

[
"AB01-E-1000-0"
"AB01-T-1050-0"
"AB02-W-1000-0"
...
]

提前致谢

标签: javascriptarrays

解决方案


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);


推荐阅读