Reverse the log of an array

How can I reverse an array in JavaScript, with each item on a new line?

function logReverse(input) {
    let reverse = input.reverse();
    return reverse;
}
// The current implementation does not display items on different lines
logReverse(['HTML', 'CSS', 'JavaScript']);

I want the output to be like this when logged IN MY CONSOLE **Each on a new line:

JAVASCRIPT
CSS
HTML

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

Any suggestions or solutions are appreciated. Thank you!

Answer №1

To achieve the desired result:

React
Sass
JavaScript

Using the supplied input (Your array):

['JavaScript', 'Sass', 'React']

You need to reverse the original array and iterate through it, using console.log.

You can try employing this function:

function logReversed(array) {
  // Reverse the array provided
  const reversedArray = array.reverse();

  // Output each element
  reversedArray.forEach((item) => {
    console.log(item);
  });
}

logReversed(['JavaScript', 'Sass', 'React']);

If you prefer not to use functions, an alternative approach with a loop is also feasible.

function logReversed(array) {
  const lastIdx = array.length - 1;

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

logReversed(['JavaScript', 'Sass', 'React']);

Hoping this solution proves helpful. Best of luck!

Answer №2

In order to achieve that result, you can either iterate through the array and use console.log for each element:

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

Alternatively, you can concatenate the elements into a single string using a newline character as the separator.

console.log(logInReverseOrder(['HTML', 'CSS', 'JavaScript']).join("\n"));

Answer №3

To reverse an array, you can utilize the Array.reverse() method.

var arr = logReverse(['HTML', 'CSS', 'JavaScript']);
var new_arr = arr.reverse();
print(new_arr);

Answer №4

The function provided does not log the result but instead returns it, allowing for further manipulation such as logging. One option is to use the join method to log each string on a separate line:

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

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

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

Alternatively, if you prefer the function to directly log the result, you can include the console.log statement within the function itself:

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

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

Answer №5

One possible approach is to add a line break symbol at the end of each string in your array.

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

In addition, if you name a function "logReversed", it implies that it will reverse and display the result. Otherwise, it might be confusing.

function logReverse(input) {
    console.log(input.reverse().map(str => `${str}\n`));
}
logReverse(['HTML', 'CSS', 'JavaScript'])

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Screen boundary bouncing effect upon reaching the edge

Currently, I am working on an animated project using canvas. I have successfully implemented the functionality to control the image (ship.png) with the arrow keys for different directions. However, I am facing challenges with creating a bounce effect when ...

What is the best way to declare multiple types that require specific props?

Trying to implement the following type: type DataTypes = | Link | Event | People | Article | Department | PageSearch | OfficeSearch | CatalogSearch | DocumentSearch | KnowledgeSearch; When implemented this way, it functions correctly: ...

Managing multiple websocket subscriptions with a single connection object within a Javascript function

Note: The client-side WAMP implementation is done using Autobahn.js, and promises are handled with when.js. The goal is to establish a re-usable code structure where only one websocket 'session' or connection exists. Whenever a developer wants t ...

Utilizing the EJS access to retrieve express variables within a JavaScript onload function

When working with variables in an EJS file, you can easily access their values. For example: <h1><%= title %></h1> Now, if you want to use the same 'title' variable in an onload JavaScript function on the same EJS page, how wo ...

What is the proper way to invoke render functions using Vue 3 composition API?

During my time with Vue 2, I would typically call render() in this manner: export default { mounted(){ ... }, render(){ ... }, methods(){ ... } } Now that I'm exploring Vue 3 and the composition API, I ...

Swapping out the initial occurrence of every word in the list with a hyperlink

I stumbled upon a fantastic script on a programming forum that almost fits my requirements perfectly. It essentially replaces specific words in a document with links to Wikipedia. However, I have run into an issue where I only want the first occurrence of ...

When validating an array in JavaScript, it is important to note that not all elements may be displayed. Only the last variable of each element will

I am encountering an issue with validating an array of objects, specifically a table with rows where each row represents an object. The problem is that no error message appears if there is an error in the middle row of the table. However, if there's a ...

Express encounters difficulties loading JavaScript files

I'm currently working on building an express web app, but I'm encountering a problem with importing a javascript file. Within board.js, there's a line const utility = require('./utility');. However, this line is causing an error: ...

Creating a popup window for multiple file uploads in ASP.NET using VB.NET

Hello, I am trying to create a popup window with multiple file upload options. When the 'UploadDocument' button is clicked, I want the popup window to appear. I have attempted to do this but it is not working as expected. Currently, the popup ap ...

What is the most efficient way to delete every other index from an Array list until all elements have been removed?

I have been struggling with this issue for quite some time and I would really appreciate some help. I need to remove all the numbers at even indices from the given input. Input = 1,2,3,4,5,6,7,8,9,10 Output should be: 1) 1,3,5,7,9 2) 1,5,7,9 3) 1,7,9 ...

Tips for triggering the button command event using JavaScript

Is there a way to activate the button command event using JavaScript? I'm not referring to the BUTTON onclick event. ...

Unable to insert form and view upon file upload click

After attempting a file upload within a form, I noticed that upon submission the data is not being inserted into the database as expected. Additionally, when trying to access the table on another page and clicking on a specific file, the redirection does n ...

AngularJS: Ensuring Controller Functions are Executed Post AJAX Call Completion via Service

Here's the code snippet I have in my service. this.loginUser = function(checkUser) { Parse.User.logIn(checkUser.username, checkUser.password, { success: function(user) { $rootScope.$apply(function (){ $rootScop ...

What is the best way to switch back and forth between Bootstrap 5.1.0 modals?

I encountered an issue where the first modal remains visible when opening the second modal within the initial popup. Can anyone explain why this is happening? Furthermore, I noticed that the backdrop for the second modal is darker, indicating that it is s ...

Avoid having #content overlap by using a double sidebar layout

My current project involves utilizing Bootstrap to design a webpage featuring two fixed sidebars and a footer. Although I have successfully positioned the sidebars and footer, I am encountering issues with preventing the #content section from overlapping t ...

Checking the validity of a JSON file extension using regular expressions

Using EXTJS, I have created a file upload component for uploading files from computer. I need to restrict the uploads to JSON files only and want to display an error for any other file types. Currently, I am able to capture the filename of the imported fil ...

Manipulate images in real-time and insert custom text using JavaScript/jQuery

Within my possession is an image depicted above. My objective revolves around dynamically altering the values present at the occurrences of L, A, and B; to achieve this, I must eliminate or conceal L, A, and B while substituting them with numerical equiv ...

What is the best way to pass my session token information between various JavaScript files on the server?

Here's the current status of my session tokens on the server: In my server.js file: app.use( session({ secret: "{ ...

What is the process for calculating the total sum of input values utilizing JavaScript?

My JavaScript skills are not perfect, and I'm struggling to calculate the total sum of values in the amount input boxes without refreshing the page. Can someone assist me with this challenge? Thank you. function Calculat ...

guiding user immediately to blog post upon successful login

I recently created a blog with a customized URL like instead of the traditional . Now, my dilemma is that I want to share this URL and have it redirect users to the login page if they are not logged in. Once they log in, I would like them to be redirect ...