How to remove the last comma when using for loop?

I have to display a message after performing validation saying that the Nationality- A,B,C already exists.


Expected Message: Nationality- A,B,C already exists.


Actual Message I’am getting now is : Nationality- A,B,C, already exists. (Need to remove comma after C)

if(error.status === 409){
  this._commonSrvc.error('Nationality- '+this.getNationality(payLoad.custBkgGrpNationality) +' already exists +'.');
        return;
      }



private getNationality(Nationalities:any)
  { let Nationalitiesstr : String ="";
    for(let i=0; i<Nationalities.length; i++)
    {
      Nationalitiesstr = Nationalitiesstr + this.nationalityData.find(x => x.libraryID == Nationalities[i].nationalityXid).libraryName + ',';
    }
    return Nationalitiesstr; 
  }

Answer

Take the comma off the end of the string. Then add a check to see if i is less than the collection length – 1. Something like…

Nationalitiesstr = Nationalitiesstr + this.nationalityData.find(x => x.libraryID == Nationalities[i].nationalityXid).libraryName;

if (i < Nationalities.length -1)
  Nationalitiesstr += “, “; 

The String.Join Method … may also work.