Printing the elements of an array in a repetitive sequence

var arr = [a, b, c];

In this specific array setup, index 0 corresponds to "a", index 1 corresponds to "b", index 2 corresponds to "c".

console.log(arr[0])  // will output > "a"
console.log(arr[1])  // will output > "b"
console.log(arr[2])  // will output > "c"

Is there a method by which if I call console.log(arr[3]) it would display "a" again, console.log(arr[4]) would show "b", and so on. For example, calling console.log(arr[42]) should give any of the three string values while following the same pattern.

Answer №1

To simplify, use the modulo operator (%) like so: arr[value % arr.length].

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

function findValue(val){
return arr[val % arr.length];
}
console.log(findValue(0))
console.log(findValue(1))
console.log(findValue(2))
console.log(findValue(3))
console.log(findValue(4))
console.log(findValue(5))
console.log(findValue(6))
console.log(findValue(42))

Answer №2

We can create a custom function to determine the correct index.

function findIndex(number){
  return number % 3; // using modulo operator
}
var array = ["apple", "banana", "cherry"];
console.log(array[findIndex(0)]);
console.log(array[findIndex(1)]);
console.log(array[findIndex(2)]);
console.log(array[findIndex(3)]);
console.log(array[findIndex(4)]);
console.log(array[findIndex(5)]);
console.log(array[findIndex(41)]);

Answer №3

We may not have exactly what you're seeking, but we do have a solution that fits your needs:

var items = ["x","y","z"];
var displayToThisAmount = function(num){
    var len = items.length;
    for(i=0;i<num;++i)
     {
         console.log(items[i%len])

     }
}

Answer №4

By utilizing the % operator, you have the ability to make a function repeat itself as many times as desired.

let items = ['apple','banana','cherry'];

let repeats = 5;

for(var j = 0; j < repeats; j++){
  console.log(items[j%3]);
}

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

Is it possible to verify the existence of several arrays of data in a MongoDB database using Node.js?

I'm trying to verify if certain data exists in a database. If the data does exist, I want to set the value of k to 1. global.k = 0 let roll = {roll0:"1616",roll1:"234"} for (let i = 0; i < inputcount; i++) { let obj1 = roll["roll" + i]; const ...

Steps for saving data to a JSON file in a React application

Looking to update a json file with some data. The current contents of the JSON file are: [{"name":"Flossi","image":"https://robohash.org/istevelitut.png?size=50x50&set=set1","price":49,"info": ...

Exploring the Methods to Filter JSON Data in Node.js

There have been significant changes in technologies over the past couple of years since I last checked answers to this question. Currently, I am dealing with JSON files that are being transmitted from a database to my server. My main concern is how to eff ...

When using jQuery, adding a class does not always trigger CSS animation

Currently facing a peculiar issue. I am utilizing jQuery to load articles from JSON and would like to dynamically add a class of 'animate' to each loaded element. $.each(jsonArticles, function (i, article) { var $articleHTML = $( ' ...

Converting MiniZinc CSP to JSON using a workaround for iterating through arrays in JavaScript

Utilizing the node.js module "Governify CSP Tools" to tackle a CSP issue has been challenging. Despite following the guidelines on defining an array from the CSP model schema (https://www.npmjs.com/package/governify-csp-tools), I have encountered syntax er ...

Check if the record already exists, if so then update it, if not then insert a new record without

I have been struggling to develop a script that will handle data from an API by inserting it into a database, updating if it already exists, and deleting any records not present in the array. I have managed to get the initial insert working, but subsequent ...

What is the best way to implement media queries for mobile phones and desktop computers?

I've come across similar questions before but still can't wrap my head around it. Here's my dilemma: I want the index page of my website to display in desktop layout on desktops and mobile jquery on mobile devices. Currently, I have set up m ...

Use jQuery to compare the input values whenever they are modified

I am trying to synchronize the input values of two inputs as they are typed in. The code I have seems to work sometimes, but not consistently. Here is the code snippet: $('#google-querynav').keypress(function() { var text = $(this).val(); ...

Change the format of the array from the initial array to the new array structure

I have a multi dimensional array that I need to convert into the array2 structure. I've tried various methods, but all of them have resulted in bulky code and lots of iteration. Is there an easier way to accomplish this task? I am new to Angular and ...

A step-by-step guide on transforming an array of objects into an array of arrays with the help of Ramda

I want to convert the following data: [ { a: 2000, b: 4000 }, { a: 8000, b: 5000 }, { a: 6000, b: 1000 } ]; Into this format: [ [ 2000, 8000, 6000 ], [ 4000, 5000, 1000 ] ]; Using Ramda library. I am able to achieve this using R.reduce functio ...

`problem encountered when attempting to sanitize HTML through the npm package known as "sanitize-html"`

After researching the documentation, I attempted to use this code snippet: const dirty = '<div>Content</div>'; const clean = sanitizeHtml(dirty); The desired result of 'clean' should be "Content", however it seems that &apo ...

How does the single-threaded nature of Node.js handle an abundance of concurrent requests?

I'm currently delving into the world of nodejs, trying to wrap my head around its single-threaded nature. Here's a pondering I have: Let's say I implement a non-blocking method and we have 20000 concurrent requests flowing in. If one request ...

Only show the directive methods when using "ng-if"

I am facing an issue with the Opentoke Library directive, particularly when I use the ng-if. The reason for implementing the ng-if is that WebRTC is not supported on IOS devices, so it displays an alert after the DOM has loaded. <div class="opentok" ng ...

What is the reason behind the linking or appearance together of src/pages in Visual Studio Code?

As I venture into the world of Visual Studio Code (VSC) and follow a Gatsby tutorial, I've noticed that every time I create a new directory, VSC seems to automatically link src/pages together. However, my preference is for pages to be a subfolder of s ...

What is the fastest method for slicing a Python list using a NumPy array of indices?

I am dealing with a standard list named a, alongside a set of indices in a NumPy array called b. (Unfortunately, I cannot convert a into a NumPy array.) Is there a more efficient way to achieve the equivalent of "a[b]" without individually extracting ea ...

Is it possible to target an iframe and display text simultaneously?

Trying to create a unique menu that interacts with an iframe and displays text in a separate div upon clicking. Example: • Menu item 1 clicked. • "https://wikipedia.org" loads in the iframe. • Address of the wikipedia page displayed in a diffe ...

What is the process of displaying JSON headers using JavaScript?

Although it may seem like a simple question, I am new to JSON. Can someone explain how to display a heading in the console? This is the code I have: var jsonstr = '{"profile":{"name" : "raj","age":"35&qu ...

Develop a new object using NodeJS within a module for a function

I am working with a file named item.js exports.itemParam = function(name, price, url, id){ this.name = name; this.price = price; this.id = id; this.url = url; }; In my www.js file, I have imported item.js like this: var item = require('../m ...

The act of binding is not functioning

Hello everyone, I am excited to be posting on stackoverflow for the first time. Recently, I have started learning ember.js and I am really enjoying it. Currently, I am working on a small project to practice my ember.js skills, but I seem to be having tro ...

Activating JavaScript in the browser only when a button is manually clicked, not by default

As I work on my website, which is currently being constructed, I rely heavily on JavaScript. However, a concern of mine is the potential for failure if a user has JavaScript disabled on their client side system. I understand that it is not possible to pro ...