Guide to repeatedly printing an array a set number of times

Consider the following array:

var arr = ['a','b','c','d'];

Your task is to prompt the user to input a number, for instance: 6, 7, 10, or any other number.

Let's assume that the user enters: 10

The desired output would be: a b c d a b c d a b

A total of 10 values should be printed using the array values in order.

The challenge here is to achieve this without utilizing any if conditions.

Answer №1

To efficiently retrieve elements from an array, utilize the modulus operator (%). More information can be found here

Here is a simple pseudo code example:

iterate through each element with index i
    output yourArray[i % yourArray.length]
end iteration

Answer №2

In the usual case:

for (let i = 0; i < input; i++) {
  console.log(array[i % array.length]);
}

Using recursion:

let func = function(input) {
  return input > 0 ? func(input - 1) + array[input % array.length] : array[0];
}

console.log(func(10));

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

Employ a variable within the fetch method to retrieve JSON data

Currently, I am in the process of developing a system that extracts specific information from a JSON file based on user input. One challenge that I am facing is how to incorporate a variable into the designated section of my code; fetch( ...

Steps to incorporate an image overlay onto a clickable button

I'm currently working on enhancing the appearance of my T-Shirt color buttons by adding a heathered image overlay. While some shirts have plain colors, I want to show a pattern overlay on others. How can I include an image for specific buttons that ar ...

Error: No schema found for the specified "User" model

Attempting to establish a connection with the MongoDB database using Mongoose and defining the model resulted in the following error message: MissingSchemaError: Schema hasn't been registered for model "User" Several approaches were taken to address ...

Using Django to load a template and incorporate a loading spinner to enhance user experience during data retrieval

In my Django project, I need to load body.html first and then dashboard.html. The dashboard.html file is heavy as it works with python dataframes within the script tag. So, my goal is to display body.html first, and once it's rendered, show a loading ...

Components with no specific branding in Vue

Creating a quiz in Vue.js with various question types: Select one Select multiple Select image Match The challenge lies in the mixing of question types within the same quiz, leading to the use of different components (<x-select-one-question>, < ...

One method of extracting an object from an array using a parameter function is by utilizing the following approach

I am searching for a specific object in an array based on the user-provided ID. var laptops = [{ "name": "Firefox", "age": 30, "id": "ab" }, { "name": "Google", "age": 35, "id": "cd", "date": "00.02.1990" }, { "na ...

What is the best way to change the date format of a JSON string to a custom format?

Hello, I am seeking advice on how to convert a JSON string date from a response into the format of "8/24/2016". I attempted to use a dateFilter.js file, but encountered errors. Here is my attempted code: Below is the dateFilter.js code that resulted in an ...

Transform an array of objects into a two-dimensional array to organize elements by their identical ids in typescript

I have a collection of objects: arr1 = [{catid: 1, name: 'mango', category: 'fruit'}, {catid: 2, name: 'potato', category: 'veg'}, {catid: 3, name: 'chiken', category: 'nonveg'},{catid: 1, name: & ...

Developing a Vue.js application with a universal variable

In the previous version of Vue.js, 0.12, passing a variable from the root component to its children was as simple as using inherit: true on any component that needed access to the parent's data. However, in Vue.js 1.0, the inherit: true feature was r ...

Using the JavaScript moment library, you can easily convert a value into seconds

Could moment.js be used to format var timeValue = '65' into 01:05? While easier to format as ('HH:MM:SS'), passing a variable as 65 and converting it into ('mm:ss') results in '01:00' instead of '01:05'. C ...

Issue: Utilized more hooks than in the previous render cycle

After the initial load of a component that renders and makes data calls on the client side, everything works fine. However, when clicking a "see more" button to make another call, an error occurs in the console indicating that there are too many hooks be ...

Is it possible to send fetch requests to dynamic endpoints, such as remote URLs that don't have CORS enabled? Can the http-proxy-middleware library handle using variables in endpoint targets?

Using the fetch('htp://list-of-servers') command, a list of URLs is retrieved: test1.example.com test3.example.com test5.example.com The next step involves executing a fetch() function on each of these URLs: fetch('test1.example.com' ...

Using jQuery to detect clicks and conditionally execute code

I am currently attempting to determine if an ID has been clicked. If it has, I want to perform a specific action, otherwise, another action should take place. The second part of my code is functioning correctly, but the click event detection does not seem ...

I will not be accessing the function inside the .on("click") event handler

Can someone help me troubleshoot why my code is not entering the on click function as expected? What am I missing here? let allDivsOnTheRightPane = rightPane.contents().find(".x-panel-body-noheader > div"); //adjust height of expanded divs after addi ...

How to deal with jQuery's set val() behavior on SELECT when there is no matching value

Let's say I have a select box like this: <select id="s" name="s"> <option value="0">-</option> <option value="1">A</option> <option value="2" selected>B</option> <option value="3">C</option> </ ...

Tic-Tac-Toe: The square's value stays unchangeable

Currently, I am working on creating a tic-tac-toe game using pure vanilla Javascript, so I am aiming to keep it as simple as possible. I have run into an issue and need some guidance. The main requirement is that once a square has been clicked and filled ...

Encountering issues with jQuery AJAX POST request

I'm currently facing an issue while attempting to send a post request to parse JSON formatted data into my webpage. Here's an example of the query: $("#click").click(function () { $.ajax({ type: "POST", url: "http://ut-pc-236 ...

The program I wrote successfully generates the desired output, however, there are additional numbers included as well

Having developed a program that compares elements of two arrays and creates a new array with unique elements, I encountered an issue. While the code compiles without errors, upon running it, I noticed additional random numbers in the output. This unexpecte ...

Running a CSS keyframes animation can be achieved by removing the class associated with it

Is there a way to reverse the CSS animation when a class is removed? I'm trying to achieve this on my simple example here: https://codepen.io/MichaelRydl/pen/MWPvxex - How can I make the animation play in reverse when clicking the button that removes ...

Troubleshooting problem with binding and calling jQuery javascript functions

I created a custom JavaScript function called 'mc_change' and I want it to be triggered when a textbox's value changes. <input type="text" id="mc_val" onchange="javascript:mc_change();" /> Unfortunately, the function is not working ...