Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to map a List of items 'n' times, but loop back to the beginning each time

I’m fairly new to React, so there is probably just an easier way to do this.

But I have a List of items

const NOTES = [
  { id: 0, val: "C" },
  { id: 1, val: "C#" },
  { id: 2, val: "D" },
  { id: 3, val: "D#" },
  { id: 4, val: "E" },
  { id: 5, val: "F" },
  { id: 6, val: "F#" },
  { id: 7, val: "G" },
  { id: 8, val: "G#" },
  { id: 9, val: "A" },
  { id: 10, val: "A#" },
  { id: 11, val: "B" },
];

The requirement is that a user will give a number of notes to display.
So for example, if the user gives 14 you would display

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

C, C#, D, D#, E, F, F#, G, G#, A, A#, B, C, C#

I currently have this

  const keys = [...Array(13).keys()];
  console.log("keys: ", keys);
  return (
    <div>
      {keys.map((item) => (
        <div key={item}>{NOTES[item].val}</div>
      ))}
    </div>
  );

But because there are only 12 elements in the List, I get an error. Is there any way to make it so that when it reaches the last element in the List, I go back to the first element and continue ‘n’ times?

>Solution :

Instead of using keys.map

You can create a function

This function will receive a parameter (the number of times that you need notes in this example 14)

Then inside the func declare the NOTES array

Set a counter in 0 (let variable)

Set an empty array that you are going to fill with info after

Define a for loop that is going from 0 to the param that you defined

Inside for do an array.push
Example: myArray.push(NOTES[counter])

Execute counter++
If the counter is 11 set it to 0 again

Then outside for loop return the array

Then replace keys.map with myFunc(16).map

And each item will be the array that are you looking for

Hope this helps you to find the right solution

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading