4

I have a service that contains information about members. One of the variables here is the team string.

In my component, I call the service method to put the information in a variable before showing it in the component.

I would like to fill the variable "teams" in my component with an unique list of teams in the service. This should take into account writing (so I would use toUpperCase()).

My service:

import { Injectable } from '@angular/core';

@Injectable()
export class UserinfoService
{
    //methods or services
    getMembers()
    {
        return [
            {
                imageUrl: "../assets/images/filler.jpg",
                firstName: "filler",
                lastName: "filler",
                team: "TEAM A",
                number: "+123456798",
                bio: "Lorem ipsum dolor sit amet,...",
                isActive: true
            },
            {
                imageUrl: "../assets/images/filler.jpg",
                firstName: "filler",
                lastName: "filler",
                team: "TEam A",
                number: "+123456798",
                bio: "Lorem ipsum dolor sit amet,...",
                isActive: false
            },
            {
                imageUrl: "../assets/images/filler.jpg",
                firstName: "filler",
                lastName: "filler",
                team: "TEAM B",
                number: "+123456798",
                bio: "Lorem ipsum dolor sit amet,...",
                isActive: true
            },
        ];
    }
    //constructor
    constructor()
    {
    }
}

my component:

import { Component, OnInit } from '@angular/core';
import { UserinfoService } from '../services/userinfo.service';


@Component({
  selector: 'app-teammembers',
  templateUrl: './teammembers.component.html',
  styleUrls: ['./teammembers.component.css']
})
export class TeammembersComponent implements OnInit
{
    //props
    teammembers: any[];
    teams:any[];

    constructor(userinfoService: UserinfoService)
    {
        //getData
        this.teammembers = userinfoService.getMembers();
    }            

  ngOnInit() {
  }
}
OldGrey
  • 83
  • 1
  • 1
  • 11
  • `this.teams = uniq(this.teammembers.map(member => member.team))`. You can write `uniq` yourself, or use a library. –  Jul 28 '17 at 12:22
  • 1
    `[...new Set(this.teammembers.map(m => m.team))]` – Weedoze Jul 28 '17 at 12:25

1 Answers1

10

With ES6, you can achieve this in one line. Below is an example:

this.teams = this.teammembers
                 .map(item => item.team)
                 .filter((value, index, self) => self.indexOf(value) === index)
FAISAL
  • 33,618
  • 10
  • 97
  • 105