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 ? ',<br />' : ', ');
}
But to avoid comma (or comma and <br />
) in the last iteration now is:
function formatNumberSelected(number, i, array) {
var toReturn = number.number + " [" + number.amount() + "]";
if ((i + 1) < array.length) {
if (i % 5 === 4) toReturn += ',<br />';
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 = ',<br />';
else SEPARATOR = ', ';
}
return toReturn;
}
number [quantity]
in an array, then apply a join on this array with,
. Then add<br />
after every fifth comma. \$\endgroup\$