I want to group the array of object in typescript. I did it in traditional or imperative way as follows:
public datas: Data[];
public dtoMap: Map<String, DataDTO[]> = new Map<String, DataDTO[]>();
private groupBy(): void {
for (let item of this.datas) {
let valueList: DataDTO[] = this.dtoMap.get(item.type);
if (isUndefined(valueList) || valueList === null) {
valueList = new Array<DataDTO>();
}
valueList.push(convertToDTO(item));
this.dtoMap.set(item.type, valueList);
}
}
But in Java, I wrote similar method as follow:
public Map<String, List<DataDTO>> getDataMap(String defId, List<Data> datas) {
return datas.stream().map(item -> convertToDTO(defId, item)).collect(Collectors.groupingBy(DataDTO::getType, Collectors.toList()));
}
Can you help to improve the typescript method? What is the best way to group the array of objects with a property in TypeScript? Thanks
.collect(Collectors.toList()).stream()is completely redundant.toList()in thegroupingBy()collector; it's the default.