0

I'm writing an app on TypeScript I am using JSON array like:

data = [{"name":"dog",
            "line":1,
"order":1},
            {"name":"cet",
            "line":1,
"order":2},
            {"name":"red",
            "line":2,
"order":1},
            {"name":"green",
            "line":2,
"order":2},
            {"name":"elephant",
            "line":1,
"order":3}]

I want to group the array by "line" and sort in ascending order and each object in "line" sort by "order" and display it on the HTML page such that each "line" will be in a separate row .

<div *ngFor="let d of data" >
   <div *ngFor="" class= "row">
      <span >{{d.name}}</span>
   <div> 
<div> 

What is the best way to group and sort and then view?

1
  • What do you want the final data structure to look like? Commented Dec 20, 2020 at 20:12

1 Answer 1

1

If I were you (and if I understood correctly), I would group the elements using the .reduce() method, then sort each of the resulting arrays, and in the end create an array of entries to iterate over.

The grouping and sorting could look like this:

const data = [{"name":"dog", "line":1, "order":1},
            {"name":"cet", "line":1, "order":2},
            {"name":"red", "line":2, "order":1},
            {"name":"green", "line":2, "order":2},
            {"name":"elephant", "line":1, "order":3}];

const grouped = data.reduce((res, curr) => {
  res[curr.line] = res[curr.line] || [];
  res[curr.line].push(curr);
  return res;
}, {});

for (const group of Object.values(grouped)) {
  group.sort((a, b) => a.order - b.order);
}

const entries = Object.entries(grouped);

console.log(entries);

And in your template iterate over entries:

<div *ngFor="let e of entries" >
   <div *ngFor="let group of e[1]" class= "row">
      <span>{{group.name}}</span>
   </div>
   <span>{{e[0]}}</span>
</div>

You can see an example here

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

1 Comment

How can I have more fields to the group header? If for example I also want to display the order here: <span>{{e[0]}} {{order also here???}}</span>

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.