-2

Hi I am wondering how to return output of array horizontally instead of vertically I have tried a few different ways and I cannot get it to work. I know you can use .join and not use foreach but I am wondering if there is a way with foreach. I also know you can output it as an array or an object but that would have {} or [] in the output.

const studentsRow1 = ["Rachelle", "Jacob", "Jerome", "Greg", "Matt", "Walt"];

// Method 1
studentsRow1.forEach(function(student){
      console.log(student)

// Method 2
studentsRow1.forEach(student => console.log (`${student}`))

Current Output

Rachelle
Jacob
Jerome
Greg
Matt
Walt

Expected output

Rachelle, Jacob, Jerome, Greg, Matt, Walt

Joseph Kelly
  • 27
  • 1
  • 4
  • 1
    `console.log` doesn't do that. Each output is automatically put on a new line. You can do `console.log(a, b, c, d, ...)` to put them on the same line, but that won't work in the context of a for each. Your best bet would be to concatenate them into a single string which you log once the loop completes. [More here](https://stackoverflow.com/questions/9627646/chrome-javascript-developer-console-is-it-possible-to-call-console-log-withou/32049995) – Liftoff Jan 04 '21 at 23:11
  • Sorry guys I am a novice I have only been in programming school for 12 weeks. Just wondering what you can and can't do so sorry for asking questions that get downvoted. – Joseph Kelly Jan 04 '21 at 23:24

2 Answers2

1

If you simply need to output your array as a comma-separated string you don't need the loop at all and can just use join, as you mentioned.

const studentsRow1 = ["Rachelle", "Jacob", "Jerome", "Greg", "Matt", "Walt"];
const joinedList = studentsRow1.join(', ');

console.log(joinedList);

// output: "Rachelle, Jacob, Jerome, Greg, Matt, Walt"
  • Thanks for the reply, I wasn't sure if you could use .join in a for each loop but after the feedback I am quite certain you cannot. – Joseph Kelly Jan 04 '21 at 23:26
0

If I understood what you were saying, you can achieve it with reduce function

const studentsRow1 = ["Rachelle", "Jacob", "Jerome", "Greg", "Matt", "Walt"];
const reducer = (accumulator, currentValue) => accumulator + ', ' + currentValue;

console.log(studentsRow1.reduce(reducer));

Learn more about reduce function here Array.prototype.reduce()

Luka
  • 828
  • 9
  • 15
  • Thanks for your reply, This reducer s new concept to me, I will look into this code and see if I can better understand it! – Joseph Kelly Jan 04 '21 at 23:26