Print Array in one line

Hi, I was trying to print the array in single line.

Can’t do it. Will anybody help me?

Thank you.

function processData(input) {
  
  for (let i = 0; i < input.length; i++){
    if (i % 2 === 0){
      var evenum = input[i];
      console.log(evenum);
    }
  }
};
processData("hacker");

What do you mean by printing it in a single line? Are you trying to convert an array to a string and print that? If so, look at the .toString() or .join() methods.

I mean, to print in a column.
Current output is:

h
c
e

I want to print it as:

h c e

.join() method doesn’t seem to be working.

I tried the code as:

evenum = evenum.join(" ");
console.log(evenum);
``

It would depend on what your whole code is.

1 Like

That is whole code I pasted in my question:

function processData(input) {
  
  for (let i = 0; i < input.length; i++){
    if (i % 2 === 0){
      var evenum = input[i];
      console.log(evenum);
    }
  }
};
processData("hacker");

Hi,

Why don’t you try storing the values in an array variable and the logging that particular variable using console.log?

How do I do that?

Thanks.

You said that you tried using join but that it “didn’t work”. What was the code that didn’t work and how did it not work.

The console.log command is always going to create a new line in the console, so if you want to print the contents of an entire array on one line, you need a single console.log.

This is throwing an error. May be I am doing something wrong. Can’t figure it out.

function processData(input) {
  
  for (let i = 0; i < input.length; i++){
    if (i % 2 === 0){
      var evenum = input[i];
      evenum = evenum.join(' ');
      console.log(evenum);
    }
  }
};
processData("hacker");

Hope this does it:

function processData(input) {
var count = 0;
var evenum = ;
for (let i = 0; i < input.length; i++){
if (i % 2 === 0){
evenum[count] = input[i];
count++;
}
}
console.log(evenum)
};

processData(“hacker”);

join is an array method. evenum is a number. I’m starting to think that you might not understand arrays well. I suggest reviewing that material.

2 Likes

Thank you for your efforts. I really appreciate it.

1 Like