-1

How can I stop adding comma when at last element such as this ABC1 should not add comma. ArrayOutput code sample here >>>Sample

  methods:{
    test(){
      this.Aarray.forEach((value)=>{
        this.Codes += value.Code +',';
      });
      console.log(this.Codes);
    }
  },
  data(){
    return{
      Codes:'',
      Aarray:[
        {Code:'ABC12345'},
        {Code:'ABC1234'},
        {Code:'ABC123'},
        {Code:'ABC12'},
        {Code:'ABC1'},
      ]
    }
  }
Meow
  • 141
  • 9
  • 3
    `this.Aarray.join(',')` – pilchard Mar 01 '23 at 09:28
  • also [Removing last comma](https://stackoverflow.com/questions/30098089/removing-last-comma) or [How to Remove last Comma?](https://stackoverflow.com/questions/2047491/how-to-remove-last-comma) etc – pilchard Mar 01 '23 at 09:32

2 Answers2

0

Trivially, we can simply slice off the final dangling comma.

methods: {
    test() {
        this.Aarray.forEach((value) => {
            this.Codes += value.Code +',';
        });
        console.log(this.Codes.slice(0, -1));
    }
},
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

You can simply use a separator variable:

methods: {
    test() {
        let sep = '';
        this.Codes = '';
        this.Aarray.forEach((value) => {
            this.Codes += sep value.Code;
            sep = ', ';
        });
        console.log(this.Codes);
    }
},

In this way separator can be complex.

HINT: I think test() must reset this.Codes everytime need to build up.

g.annunziata
  • 3,118
  • 1
  • 24
  • 25