我有一张地图。检查地图上的连续键值,我需要隔离键并插入新数组。
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"
}
];
你可以reduce
entries
的Map
并根据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
设置为true
(TypeScript 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)