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?
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?
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));
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.
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);
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.
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.
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
data() { return: { user: {}, userName: "", userAge: "" } }, methods: { saveUserName: function() { this.userName = this.newUserName; this.$refs.userNameModal.hideModal(); this.$ ...
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> & ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
I am facing an issue with my configuration object: jwtOptionsProvider.config({ tokenGetter: (store) => { return store.get('token'); }, whiteListedDomains: ['localhost'] }); In strict mode, I ...
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 ...
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 ...
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 ...
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 ...
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'. ...