1

I am trying to groupby an array of objects w.r.t to one property of the object. What is the best way to acheive it? sample:

{ 
name: "India",
capital: "New Delhi",
cities:[{
name: "city1",
state:"state1"
},
{
name:"city3",
state:"state2"
}
....
{
name:"city56",
state:"state1"

}]
 }

What's the best way to display it grouped by state? Should I use pipes or group the array using typescipt? Is there grouping pipe available in angular4?

2 Answers 2

2

There are several ready to use pipe collections for Angular2+ which include groupBy pipes. Two possible examples are:

ng-pipes

<div *ngFor="let item of items | groupBy: 'state'">

angular-pipes

<div>{{ arrayObject | groupBy: 'state' }}</div>
Sign up to request clarification or add additional context in comments.

Comments

0

You can use lodash like this:

_.groupBy(myCityList, 'state')

Note that myCityList is the internal list that has the state property, like so:

const myCityList = [
    {
        name: "city1",
        state:"state1"
    },
    {
        name:"city3",
        state:"state2"
    },
    {
        name:"city56",
        state:"state1"
    }];

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.