Explore an associative array in a circular list format

I have a unique requirement to traverse through an associative array like a circular list. The associative array is structured as follows:

array = {item1:array(...), item2:array(...), ...}

When I reach the end of one array, I want it to seamlessly transition to the next element and continue exploring the arrays in a circular manner. The same applies when reaching the last element; it should loop back to the initial element.

To achieve this functionality, I initialize my array using the following approach:

// Construct the associative array

Prot.prototype.additem = function(itemName, itemArray)
{
    this.array[itemName] = itemArray; // where itemArray is an array
}

// Set the starting currentItem of the associative array for exploration (Can start at any key)

Prot.prototype.init = function(itemName)
{
    this.currentItem = this.array[itemName];
    this.currentItemArray = 0; 
}


Prot.prototype.next = function()
{   
    // Here, I navigate through the first array associated with the first key of my associative array
    var index = this.currentItem.indexOf(this.currentItemArray);
    index = index + 1;
    this.currentItemArray = this.currentItem[index];
    if (index == (this.currentItemArray.length - 1)) 
    {   
        // Upon reaching the end of the array corresponding to the first key, move on to the second key
        return false;
    } 
    else {
        return true;        
    }

}

// A set interval is added at the end to automate the process without requiring a loop

Answer №1

In order to determine the next item in an array, it is essential to have a separate array containing the desired order of items.

Consider the following potential approach:

class Ordering {
    constructor() {
        this.itemNames = [];
        this.items = {};
        this.hasData = false;
        this.currentIndex = 0; 
    }
    addItem(itemName, itemArray) {
        if (itemName in this.items) throw "duplicate entry";
        this.items[itemName] = { data: itemArray, index: this.itemNames.length };
        this.itemNames.push(itemName); // maintain order
        if (itemArray.length) this.hasData = true;
    }
    initialize(itemName) {
        this.currentItem = this.items[itemName];
        this.currentIndex = 0; 
    }
    retrieveNext() {
        if (!this.hasData) return;
        if (!this.currentItem) this.currentItem = this.items[this.itemNames[0]];
        var data = this.currentItem.data[this.currentIndex++];
        while (this.currentIndex >= this.currentItem.data.length) {
            this.currentItem = this.items[this.itemNames[(this.currentItem.index+1) % this.itemNames.length]];
            this.currentIndex = 0;
        } 
        return data;
    }
}

// demonstration
let orderingObj = new Ordering;
// adding arrays:
orderingObj.addItem("x", [10, 20, 30]);
orderingObj.addItem("y", [40, 50]);
orderingObj.addItem("z", [60, 70, 80, 90]);
orderingObj.addItem("w", [100]);
// Beginning with "y":
orderingObj.initialize("y");

// iterate from there...
for (let i = 0; i < 12; i++) {
    console.log(orderingObj.retrieveNext());
}

Answer №2

In JavaScript, while there is no built-in associative array, you can achieve similar functionality using objects. Here's a simple way to define an object and access its properties in a circular manner:

// Creating an object with 6 properties and their values:
var obj={a:123, b:456, c:789, d:666, e:777, f:888};

function getcirc(obj){
  // Using a "static variable" within the function:
  if(typeof getcirc.i=="undefined") getcirc.i=0;
  var keys=Object.keys(obj), k=keys[getcirc.i++%keys.length];
  console.log(k,obj[k]);
}

// Calling the function multiple times...
for (var n=0;n<20;n++) getcirc(obj);
  

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 could be causing the jQuery code to not function properly when the left or right keys are pressed during mousedown?

Explanation of HTML code: <div class="wrap"> </div> Description of JavaScript code: $(document).ready(function() { $("body").mousedown(function(event) { switch (event.which) { case 1: alert('hel ...

Unknown error occurred in Eventstore: Unable to identify the BadRequest issue

I'm encountering an error while using Eventstore, specifically: Could not recognize BadRequest; The error message is originating from: game process tick failed UnknownError: Could not recognize BadRequest at unpackToCommandError (\node_modul ...

Is it possible to direct users to varying links based on their individual status?

import React from "react"; import { Card, CardContent, CardDescription, CardHeader, CardTitle, } from "@/components/ui/card"; import Link from "next/link"; import { cn } from "@/lib/utils"; import { FaCircleChec ...

Discrepancy in functionality between .show() and .append() methods within JQuery

I have a container with an ID of "poidiv" that is hidden (display: none) initially. My goal is to dynamically load this container multiple times using a loop, where the maximum value for the loop is not predetermined. I attempted to achieve this using jQue ...

Eliminating blank elements from arrays using JavaScript

I'm looking for some assistance in deciphering the functionality of my code. I'm trying to create a function that will take a string as input and eliminate all letters, leaving only numbers behind. The goal is to have this function return an arra ...

Storing and accessing a collection of objects using Parcelable

I am currently dealing with a JSON file that is being parsed using Gson. The issue I am facing is that there are nested arrays within the JSON structure. Here is an example: "assets":[ { "Address":"Crator1, The Moon", "Title":"The ...

AngularJS returns an empty array following a get request

Upon sending a GET request in my code example to retrieve a response array containing data, I noticed that the array appears empty in the console of Firefox. I am uncertain about where the error might be occurring. https://i.stack.imgur.com/aRWL9.jpg Belo ...

What is the best way to refresh a page after rotating the web page?

Struggling with a challenge in Next JS - can't seem to figure out how to automatically refresh the page when it rotates const app () => { useEffect(()=>{ window.addEventListener("orientationchange", function() { window.locati ...

Unable to select any rows from my data array in JSON

Encountering an issue today - I am unable to retrieve any information from my JSON array. Here is an example of a row: [{"0":"84","id_account":"84","1":"1500","count_soleillos":"1500","2":"2018-06-26 10:19:43","date_purchase":"2018-06-26 10:19:43","3":"Do ...

Access to web API from a different domain using $http AngularJS request was blocked due to a denied cross-domain localhost

Using AngularJS hosted on an ASP.NET server. Making a call to a web API. When making a POST request to the web API without parameters, it works. However, when passing parameters to the POST request, it returns the following error: Error: XMLHttpRequest can ...

Enhanced compatibility with Touch.radiusX feature on smartphone and tablet devices

Curious if anyone knows about the level of support for this property. I am currently using the PR0C0D1N6 app on an iPhone 4 and based on the specifications, when radiusX is not supported it should default to 1. However, in my case, radiusX is showing as un ...

Animation that increments to a predetermined value

I'm trying to create a counter animation that dynamically animates a value calculated by the checkboxes selected. The calculation is working fine, but the animation is not happening. http://jsfiddle.net/dbtj93kL/ $('input[type="checkbox"]&apo ...

avoiding the initiation of a new ajax request while a previous one is still in progress

Attempting to create a function that retrieves data from a server on scroll. The function would look something like this... function onscrollend() { $.ajax({ }); } Feeling a bit perplexed about how to verify if the old .ajax() call is still in pr ...

How to create a sequence of queries to a mongoDB database (using mongoose) depending on a condition

Source Code let placeForSearch="hampi" let filteredHotelFacilities=req.body.filter //["Free Wifi"] let hotels = await Hotel.find({placeForSearch}) .where("facilities") .select(selectedProperties) .skip(pageNu ...

Interactive feature allowing all embedded YouTube videos on a webpage to play synchronously, with sound disabled, and on a continuous loop

I am in the process of developing a button that, when clicked by a user, will trigger all embedded YouTube videos on a specific webpage to start playing simultaneously, with sound muted, and set to loop. The target page for this button implementation can ...

Building a class structure with a JavaScript MVC approach - best practices

I am looking to develop a JavaScript web application using the MVC-like principle. While my code is functional, I am facing challenges in implementing it correctly. I have created a global variable called APP where I store controllers, views, and other com ...

Utilizing Http to Retrieve JSON Data in Ionic 3

Struggling with Ionic, trying to fetch data from a JSON File using HTTP, but encountering a strange error. https://i.sstatic.net/L2nVo.png Below are the relevant code snippets : src/pages/subhome/line/line.ts (The Subhome consists of multiple nested pag ...

Send a webhook post request without causing a redirection

Is there a way to send a post request to a webhook without redirecting the user directly to the webhook URL, after validating their input? ...

ngClass with multiple conditions

I am currently working on implementing the following functionality - I have two pre-set classes that are combined with some component variables successfully. However, I now need to include an additional conditional class. Although the first part is functi ...

Issue with rendering in sandbox environment versus localhost

Here's a dilemma I'm facing - I have some HTML code on my localhost that looks like this: <div> <p>Go to: <a href="www.foobar.com">here</a></p> </div> On localhost, the output is "Go to: here" with 'he ...