0

I need to reverse an array in javascript. However each item has to be on a new line.

function logReverse(input) {
    let reverse = input.reverse();
    return reverse

}
// it does not log them all on different lines
logReverse(['HTML', 'CSS', 'JavaScript'])

I need it to be returned like this IN MY CONSOLE **Each on a new line:

JAVASCRIPT
CSS
HTML

//NOT LIKE THIS 
[javascript,html,css]

Please help out

muhammad
  • 245
  • 1
  • 13

5 Answers5

3

In order to get this output:

JavaScript
CSS
HTML

Given the following input (Your array):

['HTML', 'CSS', 'JavaScript']

You must, reverse the original array, then loop through it calling console.log.

Try the following function:

function logBackwards(arr) {
  // Reverse the input array
  const reversed = arr.reverse();

  // Log each item
  reversed.forEach((element) => {
    console.log(element);
  });
}

logBackwards(['HTML', 'CSS', 'JavaScript']);

If you want to avoid using functions, a loop approach is also available.

function logBackwards(arr) {
  const lastItem = arr.length - 1;

  for (let i = lastItem; i >= 0; i--) {
    console.log(arr[i]);
  }
}

logBackwards(['HTML', 'CSS', 'JavaScript']);

Hope it helps, good luck!

Esteban Borai
  • 2,311
  • 1
  • 21
  • 27
2

To get that output, you need to either loop through the array and console.log each item:

logReverse(['HTML', 'CSS', 'JavaScript']).forEach(e => console.log(e));

Or join into a string with a newline character as the delimiter.

console.log(logReverse(['HTML', 'CSS', 'JavaScript']).join("\n"));
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
1

you can use Array.reverse()

var arr = logReverse(['HTML', 'CSS', 'JavaScript']);
var new_arr = arr.reverse();
print(new_arr);
AzamAbbasi
  • 91
  • 1
  • 9
0

I guess you could do this by appending a new line symbol to each string in your array

console.log(reversedArray.map(str => `${str}\n`))

Also, if you name a function "logReversed" than it means it should reverse and log. Otherwise, it's a bit confusing.

function logReverse(input) {
    console.log(input.reverse().map(str => `${str}\n`));
}
logReverse(['HTML', 'CSS', 'JavaScript'])
Yanis
  • 4,847
  • 2
  • 17
  • 17
0

Your function doesn't log anything, it returns the inverse so that you can do whatever you want to do with it, including logging it. You can use join to log each string in a separate line:

function logReverse(input) {
    return input.reverse();
}

var rev = logReverse(['HTML', 'CSS', 'JavaScript']);

console.log(rev.join('\n'));

Or, if you want the function to log it, just put the console.log code in it:

function logReverse(input) {
    console.log(input.reverse().join('\n'));
}

logReverse(['HTML', 'CSS', 'JavaScript']);
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55