-5

I want to add a % after each element in the array except the last. So far I have come up with this:

var array = [a, b, c];
for(var i=0; i<array.length; i++) {
      var outcome += array[i] + '%';
}

Outcome:

a%b%c%

How can I fix this so the % does not appear at the end of the outcome?

2 Answers2

2

You can use the Array.prototype.join method in order to get what you're after:

console.info(['a', 'b', 'c'].join('%'))
Phil
  • 157,677
  • 23
  • 242
  • 245
Jim McGaw
  • 768
  • 6
  • 13
-2

Check if the current element (value of i) is not the last element. If it's the last element don't concatenate a %, for all others concatenate with the %.

for(var i = 0; i < arr.length; i++) {
    if(arr[i] < arr.length -1) {
       var outcome += arr[i] + '%';
    }
}
Nick Kinlen
  • 1,356
  • 4
  • 30
  • 58