Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a unique array from a service in Angular [duplicate]

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() {
  }
}
like image 962
OldGrey Avatar asked Nov 16 '25 20:11

OldGrey


1 Answers

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)
like image 147
Faisal Avatar answered Nov 18 '25 11:11

Faisal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!