我有一张地图。检查地图上的连续键值,我需要分离键并插入新数组中。
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"
}
];
答案 0 :(得分:2)
您可以reduce
Map
中的entries
并根据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)
更新:
如果打字稿不允许您将Map
散布到数组中,则可以在tsconfig(TypeScript and Iterator: Type 'IterableIterator' is not an array type)中将downlevelIteration
设置为true
您也可以使用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)