2

I have an array of people with associated teams. I want to display all the people in the record, but I only want to display their team name once.

Meaning, if the v-for loop has encountered this particular team name, it should put it in a new temporary array to signify that it should be unique, then when it encounters that team name again, checks it through that temporary array and prevent it from showing again.

Sample HTML Code:

<div id="a-list">
     <div v-for="person in people">{{person.Name}}, {{person.Team}}</div>
</div>

Sample Vue Code:

var crew = new Vue({
el: "#a-list",
data: {
people:
  [ { "Name": "Richard","Team":"DMS"}, { "Name": "Mark","Team":"VV"}, { "Name": "Steve","Team":"VV"}, {"Name":"Koji","Team":"MZ"}, {"Name":"Jamie","Team":"VV"} ]
  }
});

Expected Output:

Richard, DMS
Mark, VV
Steve, 
Koji, MZ
Jaimie,

Is this possible to do directly from the v-for loop and not in the JS file?

Edited to show more data that are not sequential

Update: As Fabio has pointed out, the above scenario wouldn't make much sense unless the order of the team is arranged sequentially in the output first. So his answer is correct.

Artvader
  • 906
  • 2
  • 15
  • 31
  • may be you want to improve the array structure? i think if you store people in an array with company name as key, shouldn't it be better ? something like this: people: [ DMS: { "Richard" }, VV: { "Mark", "Steve", "Jamie" }, MZ: { "Koji" }, ] – Shehzad Oct 25 '18 at 07:40
  • with this output I could think that Jaimie is in MZ team, is this right? – Fab Oct 25 '18 at 07:43
  • No, Jamie is in team VV. But considering what you said about the data not making sense if they are not ordered by team, then I think you are right. – Artvader Oct 25 '18 at 07:48

1 Answers1

1

This could be a solution:

<div id="a-list">
    <div v-for="(person,index) in people"> {{person.Name}}, {{ ((index == 0) || person.Team != people[index-1].Team) ? person.Team : '' }}</div>
</div>
Fab
  • 4,526
  • 2
  • 21
  • 45
  • Oh Sorry. I think this is not a good solution. Because this only checks if the person.Team is next to each other. If the order is re-arranged, then the attribute will still repeat. – Artvader Oct 25 '18 at 07:21
  • Yes. Ideally I want to hide the team wherever in the array it appears in. – Artvader Oct 25 '18 at 07:39
  • I can consider your answer as correct since I really do need to rearrange them by team anyways. Thanks gain. Sorry for making it complicated. – Artvader Oct 25 '18 at 07:48