What is the best way to loop back to the beginning of an array after reaching the last element in JavaScript?

I have an array in JavaScript containing music notes:

const musicNotes = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'];

The user will select a note from an HTML select list, and the selected value will be stored in a variable tonalityNote.

This tonalityNote will then be passed to a function like this:

getThirdDegreeNote(tonalityNote) {
        /* Get the index of tonalityNote in the musicNotes array */
        const tonalityNoteIndex = musicNotes.indexOf(tonalityNote);
        /* Get the value at the index tonalityNoteIndex + 2 in the musicNotes array */
        return musicNotes[tonalityNoteIndex + 4];
    }

If tonalityNote is 'C' (the first element of the musicNotes array), there's no issue - it will always work.

However, if tonalityNote is 'B', the formula

musicNotes[tonalityNoteIndex + 4]
will return undefined.

Is there a way to wrap around to the beginning of the array when encountering such issues?

For instance, if I'm at the index with the value 'B' in the musicNotes array, can I ensure that

return musicNotes[tonalityNoteIndex + 4]
will actually return 'D#' (considering the array 'musicNotes' and counting + 4 from 'B' for clarity)?

I hope I have explained the problem clearly. This is causing me quite some struggle.

Thank you in advance.

Answer №1

To find the index, use the formula

(tonalityNoteIndex + 4) % musicNotes.length
. This will loop back to the beginning if the index exceeds the length of the musicNotes array.

const musicNotes = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'];
function getThirdDegreeNote(tonalityNote) {
  /* Find the index of tonalityNote in the musicNotes array */
  const tonalityNoteIndex = musicNotes.indexOf(tonalityNote);
  /* Retrieve the value at the index tonalityNoteIndex + 2 in musicNotes array */
  return musicNotes[(tonalityNoteIndex + 4) % musicNotes.length];
}

console.log(getThirdDegreeNote('C'));
console.log(getThirdDegreeNote('B'));

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

Unable to retrieve the value from the selected radio button

Below is the provided HTML: <form> <div class="form-group"> <div class="checkbox-detailed male_input"> <input type="radio" name="gender" id="male" value="male"> <label for="male"> ...

Exploring the differences between client-side and server-side data manipulation

Recently, I discovered how to access local variables from Express in client-side JavaScript: Check out this helpful thread on StackOverflow However, this discovery has brought up a new challenge for me... Now I am unsure about which data manipulation tas ...

Vue Router is not updating the router view when the router link clicked is embedded within the view

I have a section called Related Content located at the bottom of my posts page, which displays other related posts. When I click on the Related Content, I expect the router to update the page. However, it seems that although the URL changes, the view does ...

CSS to Vertically Display Input Values

Having an input field with type=number in a React application styled using styled-components, I am looking to have certain inputs display their values vertically. export const UnitValue = styled.input` ::-webkit-inner-spin-button, ::-webkit-outer-spin ...

The Div element refuses to budge from its current position on the page's layout

$("#pg2_main_display_div ").css({ top: -$("#pg2_main_display_div").offset().top }); The value generated by -$("#pg2_main_display_div").offset().top is currently -1033. Unfortunately, this code does not seem to be functioning properly as the content ...

avoiding the duplication of effects on an object when new objects are added via ajax

Currently, I am facing a minor issue with an application that I am working on. The problem arises on a particular page where the user can edit a document by dragging modules onto the canvas area. Upon loading the page, JavaScript causes the modules to be ...

AngularJS ng-focus does not function properly with iframes

Why isn't ng-focus working with iframe in AngularJS? What am I missing? Take a look at my code: <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script> <iframe src="example.com" tabindex="-1" ng-fo ...

Delete the event handler if the original selector used to set up the handler is unknown

I need to remove an event handler from the element. The current handler is added by a third-party plugin, and I want to prevent its behavior. As far as I know, the functions off() and unbind() require the original selector to be used. The issue arises b ...

Retrieve the vector3 that points in the direction of the pointerlockcontrols in Three.js

Exploring the feasibility of using the orientation of the yaw object in pointer lock controls as a direction for a raycaster. I've been experimenting with adding some basic shooter functionalities to the code. Despite trying various methods from stack ...

Understanding the default value type in React's setState method

I am new to React and facing difficulties identifying errors in my code. My goal is to display a list of users retrieved from a server using socket.io. Below is the original code snippet: // list of users const [users, setUsers] = useState() useEffect(() ...

webdriverIO encountered an unhandled promise rejection, resulting in a NoSuchSessionError with the message "invalid session id

I am currently learning how to conduct UI testing using Jasmine and WebdriverIO in conjunction with NodeJS. Below is a snippet of my test code: const projectsPage = require('../../lib/pages/projects.page'); const by = require('selenium-we ...

Exploring the inner structure of an STL Object with the power of three.js

Currently, I am attempting to create a cross section of a heart model that I have imported using the STLLoader function in three.js. To achieve this, I am experimenting with the ThreeCSG wrapper for the csg.js library, similar to the approach outlined in t ...

The TypeScript function was anticipating one argument, however it received two instead

Can you help me fix the issue with my createUser() function? Why am I unable to pass parameters in Smoke.ts? Login.ts : interface User { url: string, email: string, } class Test{ async createUser(user: User) { await Page.setUrl(user.url); aw ...

When working with Vuejs, if you try to use "axios" in a .js file, you may encounter an error

I am currently working with VueJS and attempting to send a GET request to my API. I am using axios, but encountering an issue when trying to import it. If I use require for the import, I receive this error: Uncaught ReferenceError: require is not defined. ...

Activate Form Submission from Child Component Using Parent Button in React

Looking to achieve Form submission from a Child Component through a button within the Parent component, which is a Slide with a Next Button. The Child Component is displayed on one page of the Slide. The goal is: When the Next Button on the Parent compone ...

Combining two JSON objects with sailsjs-nodejs to create a single merged object

Hello everyone, I am a beginner with Sailsjs-Nodejs. Currently, I have two JSON Objects in my controller that I need to merge/join in order to create a third object to send as a response. The output when using res.send(obj1) is: [ { total_fare: "37 ...

Tips for saving a string value in a JSON file using Node.js:

Seeking assistance with a Javascript and node.js problem as I am new to these technologies. I need help resolving an issue related to updating the key 'title' in the file 'testdata.json' for the set 'LANG>TEST2>Default'. ...

Is there a way to retrieve a returned value from a `.ajax` request in the `done()` function in JavaScript?

Hey there! I've got a cool function that spits out the name of a person for you. Check it out below: function getName(ID){ return $.ajax({ url:url, data: ID, type: 'get', dataType: 'json' }) ...

Bringing in functions - NodeJS - non-HTML

Currently, I am in the process of learning automation for my job and have hit a roadblock. In times like these, stackoverflow has proven to be a life-saving resource :) My current task involves writing a Selenium test in VisualStudio using JavaScript (nod ...

What are some ways I can implement lighting techniques similar to those used in clara.io within Three

Currently, I am displaying an object that I downloaded from calra.io, but I am struggling to make it look like the one shown in clara.io. I have experimented with various types of lights in three.js, such as spotLight and HemisphereLight, but I haven&apos ...