Tips for iterating through/range over an array depending on the initial point?

var ZODIAC = ["RAT", "OX", "TIGER", "RABBIT", "DRAGON", "SNAKE", "HORSE", "SHEEP", "MONKEY", "ROOSTER", "DOG", "PIG"];
var STARTING_ZODIAC = "MONKEY";

Is there a way to output the elements in the array that start with Monkey and end with Sheep?

Answer №1

To ensure that your index variable cycles back to 0 when it reaches the end of the ZODIAC array, you can utilize the modulo operator:

const ZODIAC = ["RAT", "OX", "TIGER", "RABBIT", "DRAGON", "SNAKE", "HORSE", "SHEEP", "MONKEY", "ROOSTER", "DOG", "PIG"];
const STARTING_ZODIAC = "MONKEY";
const startIndex = ZODIAC.indexOf(STARTING_ZODIAC);

console.log(STARTING_ZODIAC);
for (let i = startIndex + 1; i !== startIndex; i = (i + 1) % ZODIAC.length) {
  console.log(ZODIAC[i]);
}

Alternatively, you can reorder the sections of the array using the slice method to achieve the same result:

const ZODIAC = ["RAT", "OX", "TIGER", "RABBIT", "DRAGON", "SNAKE", "HORSE", "SHEEP", "MONKEY", "ROOSTER", "DOG", "PIG"];
const STARTING_ZODIAC = "MONKEY";
const startIndex = ZODIAC.indexOf(STARTING_ZODIAC);

[
   ...ZODIAC.slice(startIndex),
   ...ZODIAC.slice(0, startIndex)
].forEach(str => console.log(str));

Answer №2

There are a total of 6 answers provided, however none of them take into consideration the solution that seems obvious to me:

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

You can iterate through the loop 12 times and utilize the modulus operator to cycle through the numbers in a seamless manner: 4, 5, 6...10, 11, 0, 1, 2, 3.

Answer №3

To easily display the zodiac signs, simply print them out starting from the chosen sign and then in reverse order.

function displayZodiacs(chosenSign, zodiacSigns) {
  const startIndex = zodiacSigns.indexOf(chosenSign);

  // Print from start to end of array
  for (let i = startIndex; i < zodiacSigns.length; i++) {
    console.log(zodiacSigns[i]);
  }

  // Print from beginning of array to chosen sign
  for (let i = 0; i < startIndex; i++) {
    console.log(zodiacSigns[i]);
  }
}

displayZodiacs(CHOOSEN_SIGN, ZODIAC_SIGNS);

Answer №4

Here's another interesting approach:

let zodiacDouble = ZODIAC.concat(ZODIAC);
let initial = ZODIAC.indexOf(START_ZODIAC);

for (let j = 0; j < ZODIAC.length; j++) {
  console.log(zodiacDouble[initial + j]);
}

This method involves duplicating the array and then displaying 12 elements starting from a specified index.

Answer №5

One of the most direct solutions in my opinion involves a do-while loop that starts at a specific index and loops until it reaches back to that same index. Using a do-block is a straightforward way to handle this particular situation:

const ZODIAC = ["RAT", "OX", "TIGER", "RABBIT", "DRAGON", "SNAKE", "HORSE", "SHEEP", "MONKEY", "ROOSTER", "DOG", "PIG"];
const STARTING_ZODIAC = "MONKEY";

let i = start_ndx = ZODIAC.indexOf(STARTING_ZODIAC);

do {
  console.log(i, ZODIAC[i++])
  i == ZODIAC.length && (i=0)
} while (i!==start_ndx)

Note: In my perspective, other answers appear overly complex by using modulo or inefficient by copying values and creating new arrays. The approach shown above avoids both complexities and inefficiencies, making it easier to maintain.

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

What is the best way to retrieve local variables within a React function?

I keep encountering this issue where I get a TypeError saying that the property 'classList' cannot be read for an undefined value, and this error occurs even before the functions are executed. The specific line causing the error is slide[n].class ...

Sending a custom `GET` request with multiple IDs and additional parameters using Restangular can be achieved by following

I'm trying to send multiple ids along with other parameters using my custom customGET method. However, the implementation seems to be incorrect: var selection = [2,10,20]; // Issue: GET /api/user/export/file?param1=test&ids=2,10,20 Restangular.a ...

Employing IF conditions within a form to refine options

I am looking to streamline the options in my form based on the car and transmission selected. I have set up the form, but I am struggling with the JavaScript code. I need help figuring out how to only display certain color options when Car 1 is chosen alon ...

Exploring MongoDB by querying elements within an array

In a NodeJS environment, suppose we have an array called SelectedAnimals with elements like "cat", "mouse", "bird". How can we create a query to display all elements from a database collection where the key animal matches any of these array elements? For ...

Angular - Brilliant time selection tool (BTS) The TimePicker feature fails to automatically switch to selecting minutes after choosing the hour

I'm currently implementing the Amazing time picker in my app and I'm facing an issue where it doesn't automatically switch to minutes after selecting the hour. component.html <input type="time" atp-time-picker formControlName="time" cla ...

Exploring the potential of Framework7 in Single Page Applications: optimizing performance by preloading

I'm currently working on developing a web application using Framework7. Framework7 offers routing APIs for navigating between HTML pages. It seems that the pages are loaded dynamically through AJAX requests. I am curious if it is possible to preload ...

Utilize vue.js to save the components of an object

data() { return: { user: {}, userName: "", userAge: "" } }, methods: { saveUserName: function() { this.userName = this.newUserName; this.$refs.userNameModal.hideModal(); this.$ ...

Having trouble with basic authorization for Facebook API using JavaScript?

I am having an issue with my source code. When I run it, I receive an alert that says "No Response" and then the Facebook page displays an error message stating "An error occurred with MYAPP. Please try again later" <div id="fb-root"></div> & ...

Retrieve a specific line of code from a snippet of JavaScript

I am looking to extract a specific line of code from a script that I am receiving via ajax... The line in question is new Date(2010, 10 - 1, 31, 23, 59, 59) found within the following snippet: jQuery(function () { jQuery('#dealCountdown').count ...

Express application receiving repetitive post requests

Recently, I have been working on developing a YouTube video conversion app that utilizes youtube-dl for streaming videos from YouTube and saving them. Everything was going smoothly until I encountered an issue when trying to stream a video that exceeded on ...

Why is my v-model not being updated when using a radio button in Vue.js?

After reviewing the documentation, I attempted to implement the code provided. While I am able to successfully retrieve data for enquiryDesc, I am consistently getting a value of 5 for the rating field. I even experimented with changing the radio group to ...

Unsuccessful attempt at aborting an Ajax request

Currently, I have developed a basic live search feature using jQuery ajax to search through a JSON file on the server and display a list of events. The script is programmed to show a list of events that were previously displayed on the page if the search ...

Tips for transferring objects from JavaScript/jQuery/angular to an action function

Issue at Hand: I currently have a form with 10 fields, and the challenge lies in passing these 10 values to an ASP.Net MVC Action. To tackle this, I utilize ng-click to send these values to the action which then forwards them to the database. I find myse ...

Deactivate the button for each package based on a specific PHP value

Are you looking to purchase a package or multiple packages? The available packages are displayed in the table below. I would like to implement a feature where once a user buys a package, the corresponding button for that package is disabled. Here is my cu ...

Summoning within a rigorous mode

I am facing an issue with my configuration object: jwtOptionsProvider.config({ tokenGetter: (store) => { return store.get('token'); }, whiteListedDomains: ['localhost'] }); In strict mode, I ...

Tips for Embedding External JavaScript and URLs in Joomla Protostar Template

I'm interested in incorporating a hamburger menu into my Joomla protostar template, similar to the one featured on this URL: ['https://codepen.io/PaulVanO/pen/GgGeyE'] This will provide me with a fullscreen hamburger menu for both desktop ...

JavaScript does not recognize jsPDF

After importing the jsPDF library, I attempted to export to PDF but encountered a JavaScript error stating that jsPDF is not defined. I tried various solutions from similar posts but none of them seemed to work for me. You can find the fiddle here: https ...

Refresh gif without having to reload it in Internet Explorer 11

I'm attempting to create a feature where a gif restarts when clicked by the user, without needing to reload it (due to the heavy size of the gif which is preloaded for my application). The current code functions flawlessly on Chrome and other "modern ...

Issue with parsing an empty array in a Discord bot built with Node.js

Within this API, there exists an empty array marked with a red underline. Sometimes it's void of content, but other times it contains data. My goal is to display Item Spells: there are no effects on this item. when the array is empty. However, instead ...

Is there a way to create a div that resembles a box similar to the one shown in the

Hello, I am attempting to achieve a specific effect on my webpage. When the page loads, I would like a popup to appear at the center of the screen. To accomplish this, I have created a div element and initially set its display property to 'none'. ...