有没有有效的方法来将数据设置为MapObject?

时间:2019-12-12 14:09:07

标签: javascript reactjs typescript algorithm

我想重新制作数组并对其排序。 是否可以使用“ reduce”代替“ forEach”或“ map”? 返回beeProps.valueInfos.reduce(reduce())会很棒。

[Date,Onject] ---> [Number,Object] ---我想将相同的“ Number”对象获取到数组中---> [Number,Object []]

我相信这里的人是如此聪明……有人可以找到一个好方法。


//Sample IO

  type Info = {
    title: string;
    InfoMap: Map<Date, Slot>; 
  };

  type Slot =
  | {
      kind: "on";
    }
  | {
      kind: "off";
    };

    let date1 = new Date(1999, 11, 31, 20);        
    let date2 = new Date(1999, 11, 31, 21);        
    let date3 = new Date(1999, 11, 31, 22); 
    let date4 = new Date(1999, 11, 31, 23);  

    const sampleInfoDetailMap:Map<Date, Slot> = new Map();
    sampleInfoDetailMap.set(date1,{kind: 'on' as const})
    sampleInfoDetailMap.set(date2,{kind: 'on' as const})
    sampleInfoDetailMap.set(date3,{kind: 'off' as const})
    sampleInfoDetailMap.set(date4,{kind: 'on' as const})

    const sampleInfoDetailMap2:Map<Date, Slot> = new Map();
    sampleInfoDetailMap2.set(date1,{kind: 'on' as const})
    sampleInfoDetailMap2.set(date2,{kind: 'off' as const})
    sampleInfoDetailMap2.set(date3,{kind: 'off' as const})
    sampleInfoDetailMap2.set(date4,{kind: 'on' as const})

    console.log(date1.getTime());
    console.log(date2.getTime());
   let sampleInfo:Info = {title:"test1"  ,InfoMap:sampleInfoDetailMap}
   let sampleInfo2:Info = {title:"test2"  ,InfoMap:sampleInfoDetailMap2}
   let info:Info[] = new Array();

    //ideal Output is 
    //numer => Date.getTime() : number;
    //Map<number,Slot[]>
    const idealResult:Map<number,Slot[]> = new Map();

   //[946638000000 , [on,on]
    //[946641600000 , [on,off]
//note: 946638000000 is 1999, 11, 31, 20. 946641600000 is 1999, 11, 31, 21

1 个答案:

答案 0 :(得分:1)

由于您的示例代码似乎并未指定特定的输入和输出,因此我无法从您的问题中确切知道您要查找的内容。让我知道以下内容是否对您有用:

const mapKeyMaps = <KI, KO, V>(
    keyMapper: (ki: KI) => KO,
    ...inputMaps: Map<KI, V>[]
): Map<KO, V[]> =>
    ([] as Array<[KI, V]>).concat(...inputMaps.map(m => Array.from(m.entries())))
        .map(([ki, v]) => [keyMapper(ki), v] as const)
        .reduce(
            (acc, [ko, v]) => ((acc.get(ko) || (acc.set(ko, []), acc.get(ko)!)).push(v), acc),
            new Map<KO, V[]>()
        );

为您的样本生成以下输出:

let info: Info[] = [sampleInfo, sampleInfo2];
const idealResult = mapKeyMaps((date) => date.getTime(), ...info.map(i => i.InfoMap))
console.log(JSON.stringify(Array.from(idealResult.entries())));
/*
[
    [946688400000,[{"kind":"on"},{"kind":"on"}]],
    [946692000000,[{"kind":"on"},{"kind":"off"}]],
    [946695600000,[{"kind":"off"},{"kind":"off"}]],
    [946699200000,[{"kind":"on"},{"kind":"on"}]]
]
*/

如果这对您有用,我将说明mapKeyMaps()的工作方式。如果没有,请编辑问题中的代码以构成minimal reproducible example,也许我可以提供更好的解决方案。无论哪种方式,祝你好运!

Link to code