基于Map创建一个数组

问题描述 投票:-3回答:1

我有一张地图。检查地图上的连续键值,我需要隔离键并插入新数组。

let map = new Map<string, string>();
map.set("SUNDAY", "1");
map.set("MONDAY", "2");
map.set("TUESDAY", "2");
map.set("WEDNESDAY", "4");
map.set("THURSDAY", "5");
map.set("FRIDAY", "5");
map.set("SATURDAY", "9");

预期输出应该是这样的:

[{
      day: "SUNDAY",
      value: "1"
    },
    {
      day: "MONDAY-TUESDAY",
      value: "2"
    },
    {
      day: "WEDNESDAY",
      value: "4"
    },
    {
      day: "THURSDAY-FRIDAY",
      value: "5"
    },
    {
      day: "SATURDAY",
      value: "9"
    }
  ];
javascript typescript
1个回答
2
投票

你可以reduce entriesMap并根据value分组。如果当前value已经存在于累加器中,则将-和当前的day附加到对象。否则,向累加器添加一个新密钥。然后使用Object.values()将累加器的值作为数组返回

const map = new Map([["SUNDAY","1"],["MONDAY","2"],["TUESDAY","2"],["WEDNESDAY","4"],["THURSDAY","5"],["FRIDAY","5"],["SATURDAY","5"]]);

const merged = [...map].reduce((acc, [day, value]) => {
  if(acc[value])
    acc[value].day += `-${day}`
  else
    acc[value] = { day, value };
  
  return acc
}, {});

const output = Object.values(merged);

console.log(output)

更新:

如果typescript不允许你将Map传播到数组中,你可以在tsconfig中将downlevelIteration设置为trueTypeScript and Iterator: Type 'IterableIterator' is not an array type

您也可以使用Map#forEach做同样的事情。此外,如果您希望day为天数范围,则可以使用另一个名为“previousValue”的变量。如果previousValue与当前值相同,则拆分已存在于day-并取第一个值。然后追加当前的day

let map = new Map([["SUNDAY","1"],["MONDAY","2"],["TUESDAY","2"],["WEDNESDAY","4"],["THURSDAY","5"],["FRIDAY","5"],["SATURDAY","5"]]);
let merged = {}, previousValue;

map.forEach((value, day) => {
  if(previousValue === value)
    merged[value].day = `${merged[value].day.split('-')[0]}-${day}`
  else
    merged[value] = { day, value };
  
  previousValue = value;
})

const output = Object.values(merged)

console.log(output)
© www.soinside.com 2019 - 2024. All rights reserved.