1

need you help, I have this array in a "server" js file, than, with a service, is stored in a allplayers = []; I want to filter the array so only the jazz players will remain (in players = []; ) used the code below. have any idea why it does not work? thanks

var players = [
    {team: 'bulls', fullName: 'Kerr', position: 'SG', ranking: '7', id: '1' },
    {team: 'jazz',fullName: 'stockton', position: 'PG', ranking: '9', id: '2'},
    {team: 'jazz',fullName: 'malone', position: 'PF', ranking: '8', id: '3'}
];

export class PlayersComponent implements OnInit {
  players = [];
  allplayers = [];
  bullsPlayers = [];

  constructor(private _playerService: PlayerService) {}

  filterjazzplayers(){
    for (let i = 0; i < this.allplayers.length; i++) {
        if (this.allplayers[i].team == 'jazz') {
          this.players.push(this.allplayers[i]);
        }
    }
  }

  ngOnInit (){
    this._playerService.getPlayers()
    .subscribe(
      allplayers => this.allplayers = allplayers,
      error =>  console.log(<any>error)
    );

    this.filterjazzplayers();
  }
Jamin
  • 1,362
  • 8
  • 22
lili666
  • 13
  • 1
  • 1
  • 3

1 Answers1

0

I could be wrong, but I think the problem may happen when you are creating new arrays with the same name. It might not be able to tell the difference between the local players array and the starting players array. The following code works fine as simple javascript in an html file. Hopefully this helps you find where you are having problems.

<!DOCTYPE html>
<html>
<script>
var players = [
    {team: 'bulls', fullName: 'Kerr', position: 'SG', ranking: '7', id: '1' },
    {team: 'jazz',fullName: 'stockton', position: 'PG', ranking: '9', id: '2'},
    {team: 'jazz',fullName: 'malone', position: 'PF', ranking: '8', id: '3'}
];

  var newPlayers = [];

  function filterJazzPlayers()
  {
    for(let i = 0; i < players.length;  i++)
    {
       if(players[i].team == 'jazz')
       {
          newPlayers.push(players[i]);
       }
    }
  }

  filterJazzPlayers();
  for(var j = 0; j < newPlayers.length; j++)
  {
    console.log(newPlayers[j].fullName);  
  }



  </script>
  <html>
Jamin
  • 1,362
  • 8
  • 22