function currentLine(katzDeliLine) {
if (katzDeliLine.length > 0) {
var textToPrint = \"The line is currently: \"
for (var crrLine = 0; crrLine &
function currentLine(katzDeliLine) {
if (katzDeliLine.length > 0) {
var textToPrint = "The line is currently: "
for (var crrLine = 0; crrLine < katzDeliLine.length; crrLine++) {
textToPrint = textToPrint + (crrLine + 1)+". "
+katzDeliLine[crrLine]+","
}
return textToPrint.replace(/,\s*$/, "");
} else {
return "The line is empty"
}
}
var lineofpeople = ["katrina", "kevin", "vincent"]
console.log(currentLine(lineofpeople));
You can use regex to remove the last comma
$
is for matching the end of the string
let line = 'string1, string2, string3, string4, string5,'
console.log(line.replace(/,$/g,''))
Remove the last part of the returned string using textToPrint.slice(0,-1)
function currentLine(katzDeliLine) {
if (katzDeliLine.length > 0) {
var textToPrint = "The line is currently: "
for (var crrLine = 0; crrLine < katzDeliLine.length; crrLine++) {
textToPrint = textToPrint + (crrLine + 1)+". " +katzDeliLine[crrLine]+","
}
return textToPrint.slice(0,-1);
}
else {
return "The line is empty"
}
}
var lineofpeople = ["katrina", "kevin", "vincent"]
console.log(currentLine(lineofpeople));
You could map the leading numbers with the value and join the array with comma.
function currentLine(array) {
return array.length
? `The line is currently: ${array.map((v, i) => `${i + 1}. ${v}`).join(', ')}.`
: "The line is empty.";
}
var lineofpeople = ["katrina", "kevin", "vincent"];
console.log(currentLine(lineofpeople));
console.log(currentLine([]));
An easy solution is using template literals and join().
Here you should pay attention that it's not single quote but a backtick.
var lineofpeople = ["katrina", "kevin", "vincent"]
const emptyLine = []
// Using arrow function; the code is short
const currentLine = (line) => {
return !line.length ? 'The line is empty' : `The line is currently: ${line.map((e, i) => `${i + 1}. ${e}`).join(', ')}`
}
console.log(currentLine(lineofpeople)) // expected: The line is currently: 1. katrina, 2. kevin, 3. vincent
console.log(currentLine(emptyLine)) // expected: "The line is empty"
Just check if the current index is the last one, if it is, don't add a comma:
for (var crrLine = 0; crrLine < katzDeliLine.length; crrLine++) {
textToPrint = textToPrint + (crrLine + 1) + ". " + katzDeliLine[crrLine] + (crrLine != (katzDeliLine.length - 1) ? "," : "")
}