2

I have a get request which displays an array of objects in the view via *ngFor loop. I can't seem to figure out how to get the desired result below. This is a really basic example to give you an idea of what I am trying to achieve.

data = [
    {
   "name": "Bill",
   "job" : "Builder"
 },
 {
   "name": "John",
   "job":  "Cook"
 },
 {
   "name": "Bill",
   "job" : "Builder"
 }
]

Then when the *ngFor loop is created, I'd like to be able to show something like this:

Bill [2]
John [1]

any suggestions would be greatly appreciated.

Apex
  • 227
  • 4
  • 15

2 Answers2

0

Group your results and then use them in your loop:

Fiddle

Ionel Lupu
  • 2,695
  • 6
  • 29
  • 53
0

You can create a new data structure based of your current data, counting the times a name has been visible:

data = [
    {
   "name": "Bill",
   "job" : "Builder"
 },
 {
   "name": "John",
   "job":  "Cook"
 },
 {
   "name": "Bill",
   "job" : "Builder"
 }
]

const count = {};
data.forEach(d => {
    count[d.name] = count[d.name] + 1 || 1;
});

console.log(count);

output:

{ Bill: 2, John: 1 }

You should be able to display the names and count from there.