Formatting a list with commas and occasional line breaks I have an array mapped to make a typical result string separated by commas and with numbers a bit beautified with array.map(formatNumber).

Expected format is 

number [quantity], number [quantity], number [quantity]


So 

1234 [3], 1235 [2], 2234 [1]


My mapping function was like this:

function formatNumberSelected(number, i) {
    return number.number + " [" + number.amount() + "]" + (i % 5 === 4 ? ',&lt;br /&gt;' : ', ');
}


But to avoid comma (or comma and &lt;br /&gt;) in the last iteration now is: 

function formatNumberSelected(number, i, array) {
  var toReturn = number.number + " [" + number.amount() + "]";
  if ((i + 1) &lt; array.length) {
    if (i % 5 === 4) toReturn += ',&lt;br /&gt;';
    else toReturn += ', ';
  }
  return toReturn;
}


There is a better way to make this code more readable? Seems like passing array to each iteration just to find the last index is a bit too much.

If not I find better this solution not using Array.prototype.map:

function formatNumberArray(array) {
  var SEPARATOR = '';
  var toReturn = '';
  for (var index in array) {
    toReturn += SEPARATOR + array[index].number + ' [' + array[index].amount() + ']';
    if (index % 5 === 4) SEPARATOR = ',&lt;br /&gt;';
    else SEPARATOR = ', ';
  }
  return toReturn;
}
You have serval ways to achieve this task. You can pass the length of array as well.
About the implementation you can use forEach method like this.

 function formatNumberArray(arr) {
        let output = "";
        arr.forEach((v, i, a) =&gt; {
            output += v.number + "[" + v.amount + "]" + ((i + 1) % a.length == 0 ? "" : i % 5 == 4 ? ',&lt;br /&gt;' : ', ');
        });
        return output;
    }


or you can iterate the array to the last index - 1 and then simply add the last value

function formatNumberArray(arr) {
        let output = "";
        for (let i = 0; i &lt; arr.length - 1; ++i) {
            output += arr[i].number + "[" + arr[i].amount + "]" + ((i % 5 === 4) ? ',&lt;br /&gt;' : ', ');
        }
        return output + arr[arr.length - 1].number + "[" + arr[arr.length - 1].amount + "]"
    }


I assume that the array is something like this.

  let arr = [{ number: 123, amount: 24 }, { number: 16, amount: 10 }, { number: 16, amount: 10 }, { number: 16, amount: 10 }, { number: 16, amount: 10 }, { number: 16, amount: 10 }, { number: 16, amount: 10 }, { number: 16, amount: 10 }, { number: 16, amount: 10 }, { number: 16, amount: 10 }, { number: 16, amount: 10 }, { number: 16, amount: 10 }, { number: 16, amount: 10 }]