skip to Main Content

Am try to create a JavaScript app that will get an arrays in accending order using for loop, without using the "arrays index method" .
For instance,

Index.js

arrayOfFruit = ["Banana","Pineapple","Pawpaw"],

I want the answer to be printed one after the order when the app is run, for instance once I run it for the first time I want to only see ["Banana"]
And I want to see ["Pineapple"] when I run the app second time and so on.

Please am sorry if my question is not well composed, this my first time of asking questions here, thanks.

I wasn’t able to get the right method to do it

2

Answers


  1. If you run the app in a browser, use localStorage to start a fruit’s index:

    const arrayOfFruit = ["Banana","Pineapple","Pawpaw"];
    let idx = +(localStorage.getItem('fruitIdx') ?? 0);
    console.log(arrayOfFruit[idx++]);
    if(idx >= arrayOfFruit.length) idx = 0;
    localStorage.setItem('fruitIdx', idx);
    Login or Signup to reply.
  2. Since every time you run your js code every variable will be recreated you need to rely on "persistent" storage method, nonetheless the access to desired item in array must be done with its own index (even if you are looping you need the index of the item you want to extract).

    2 easy methods can be used to store:

    1. Via query params: Your page will be open with a query param that indicates the index of the element of the array, ex.

      http://www.example.com?index=1
      

    parameter can be retrieved with:

        let params = new URLSearchParams(window.location.search);
        let arrayIndex = params.get('index');
    

    But this method require you to provide a different url every time

    1. Use local storage: On each execution of your js code you can retrieve previous index and set a new one via local storage, ex.

      let ArrayIndex = localStorage.getItem('lsKeyForArrayIndex') // you have to handle the first run where no indexes are defined in ls
      // .... your code
      localStorage.setItem('lsKeyForArrayIndex', ArrayIndex+1) // to store the new index for the next run
      
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search