0

I'm trying to figure out how to return a sentence where I have a list of items and I have to separate them with a ", ". However, if the array only contains one item, you would just return the word with no comma and if there is two words, then you would return one comma after the first word and not the last.

var conceptList = ['apple', 'orange', 'banana'];
var concepts = joinList(conceptList);

function joinList() {

  for (var i = 0; i < conceptList.length; i++) {
    if (conceptList.length) {
      conceptList[i];
    }  
  return conceptList;
  }
}

console.log("Today I learned about " + concepts + ".");

2
  • I'm voting to close this question as off-topic because turning in someone else's work as your own is dishonest. Commented Jan 15, 2018 at 23:35
  • 1
    Always append the last element of the list without a trailing comma. Hint: The loop doesn't have to iterate over the entire list. Commented Jan 15, 2018 at 23:36

1 Answer 1

1

Simple way of doing it is to append each element to a string, followed by ', ', then remove the trailing ', ' before returning the string.

/*
* Write a loop that joins the contents of conceptList together
* into one String, concepts, with each list item separated from
* the previous by a comma.
*
* Note: you may not use the built-in Array join function.
*/

var conceptList = ['apple', 'orange', 'banana'];
// a custom function written by you (you must define it too!)
var concepts = joinList(conceptList);

function joinList() {
  var str = '';
  for (var i = 0; i < conceptList.length; i++) {
    str += conceptList[i] + ', ';
  }
  
  return str.substr(0, str.length-2);
}

console.log("Today I learned about " + concepts + ".");

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.