Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Only using for loops. How do you build a function that performs like the join method?

const array = [
 "Devslopes",
 "is",
 "teaching",
 "me",
 "FOR",
 "loops",
 "and",
 "functions",
 "!"
];

const separator = " ";

function joinToString(array, separator) {
 for (let ele of array) {
  let combine = ele + separator;
 }
 return combine;
}

What I am trying to do is take the separator and add it to the end of each element of the array. In this case the separator is a space and I am trying to have the elements spaced out. The function is my current one. I am stuck on just getting each element to have a space on the end of it. That is it. I need to have a space on every element but the last one, and then I need to print the sentence or the elements of the array.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You were almost there.

If you can’t use join, you can use string concatenation, and in your return just apply a slice so the extra separator at the end is removed.

Also, your array has semicolons, but they should be commas.

const array = [
 "Devslopes",
 "is",
 "teaching",
 "me",
 "FOR",
 "loops",
 "and",
 "functions",
 "!"
];

const separator = " ";

function joinToString(array, separator) {
 let output = "";
 
 for (let ele of array) {
  output += ele + separator;
 }
 return output.slice(0, -1);
}

console.log(joinToString(array, separator))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading