I am currently developing an Angular 2 application and I have an array of objects. My goal is to return the object that has the maximum value of a specific attribute (in this case, the object with the most likes). How can I achieve this in TypeScript?
import {Player} from './player';
export const PlayersData : Player[] = [
{id:1,name:"Marc-andré Ter stegen",number:"1",post:"Goalkeeper",goals:0,assist:0,likes:10,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/150720.jpg"},
{id:2,name:"Gerrad Piqué",number:"3",post:"Defender",goals:0,assist:0,likes:10,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/27798.jpg"},
{id:3,name:"Ivan Rakitić",number:"4",post:"Midfielder",goals:0,assist:0,likes:7,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/35308.jpg"},
... additional player data ...
{id:14,name:"Samuel Umtiti",number:"23",post:"Defender",goals:0,assist:0,likes:9,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/170711.jpg"}
];
This is my TypeScript attempt:
export class DashboardComponent implements OnInit {
players : Player[] = [];
bestPlayer:Player;
constructor(private playerService : PlayerService) { }
max = 0;
bestPlayer = this.players[0];
ngOnInit() {
this.playerService.getPlayers()
.then(players => this.players = players);
for (player of players)
if (player.likes > max) {
max => player.likes;
bestPlayer => player;
}
}
}