2

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

4
  • 2
    .collect(Collectors.toList()).stream() is completely redundant. Commented Jul 13, 2017 at 5:55
  • @shmosel, I just copied my code and edited here. Thanks for highlighting it Commented Jul 13, 2017 at 6:02
  • Is your alignment correct? It looks so weird. Where is the function? Commented Jul 13, 2017 at 6:03
  • 2
    You also don't need to specify toList() in the groupingBy() collector; it's the default. Commented Jul 13, 2017 at 6:04

1 Answer 1

6

usually, for any kind of complex transformation in JS, I use lodash which can be used in TS as well. Hope the below helps you. The 'property' is the key by which you want to group the collection of items.

    import * as _ from 'lodash';

export class A {
 public datas: Data[];

private groupBy(): void {
           let groupedItems: any[] = _.groupBy(datas, 'property');
}
}

Ashley

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.