Navigating through an array with a specific starting index in JavaScript

Can anyone provide guidance on how to iterate through this array and retrieve every second "note" starting at a specific note, for example starting at F and getting f,a,c? Your help is much appreciated :)

let notes = ['c','d','e','f','g','a','b'];

Answer №1

You can implement findIndex and filter using the remainder operator in your code

Assuming you are looking for a circular wraparound

When wrapping around, I get f, a, c, e. If not wrapping, I get f, a. Did you mean to include the letter e in your expected output?

let notes = ['c', 'd', 'e', 'f', 'g', 'a', 'b'];

const findNotes = (startNote, gap) => {
  const start = notes.findIndex(note => note === startNote)
  if (start !=-1) return notes.slice(start).concat(notes.slice(0,start)).filter((note, i) => i % gap === 0)
  return "not found"
};
console.log(findNotes("f", 2))

Answer №2

To streamline this process, you can associate each note with a specific index and then duplicate the notes array to facilitate accessing values in a round-robin fashion.

let notes = ['c', 'd', 'e', 'f', 'g', 'a', 'b'],
    indexMap = notes.reduce((map, n, i) => map.set(n, i), new Map),
    twoNotes = [...notes, ...notes]

Next, define a function that retrieves the initial index from the mapping and returns the items at the next 2 indices.

function findNext(note) {
  const index = indexMap.get(note)
  return [twoNotes[index], twoNotes[index+2], twoNotes[index+4]]
}

Alternatively, for more flexibility in selecting future indices, a generic function can be created to accept the indices array as an argument.

function findNext(note) {
  const index = indexMap.get(note)
  return [0, 2, 4].map(i => twoNotes[i + index])
}

let notes = ['c', 'd', 'e', 'f', 'g', 'a', 'b'],
    indexMap = notes.reduce((map, n, i) => map.set(n, i), new Map),
    twoNotes = [...notes, ...notes]

function findNext(note) {
  const index = indexMap.get(note)
  return [0, 2, 4].map(i => twoNotes[i + index])
}

console.log(...findNext('f'))
console.log(...findNext('c'))

Answer №3

If you want your index variable to reset to 0 once it reaches the end of the notes array, you can achieve this using the modulo operator. This will give you the output f,a,c,:

let notes = ['c','d','e','f','g','a','b'];
let startIndex = notes.indexOf('f');
for (let i = startIndex; i !==  startIndex-1; i = (i + 2) % notes.length)) {
     document.write(notes[i]+",");
}

For even better performance in certain cases, there is an alternative method you can use with the for loop...

let notes = ['c','d','e','f','g','a','b'];
let startIndex = notes.indexOf('f')-2;
for (
     let i = startIndex;
     i !==  startIndex-1;
     (i = (i + 2) % notes.length)==document.write(notes[i]+",")
);

Remember: don't forget the ';' after the for loop if you're not using '{}'.

Another approach would be to rearrange the array by slicing and then iterating through it:

let notes = ['c','d','e','f','g','a','b'];
let startIndex = notes.indexOf('f');
notes = [
    ...notes.slice(startIndex),
    ...notes.slice(0, startIndex)
];

for (let i = 0; i < notes.length - 2; i += 2) {
      let note = notes[i];
      document.write(note+",");
}

Answer №4

To extract specific elements from an array starting at a certain index, you can use a for loop and specify the starting index. For instance, executing the following code will result in: 'f', 'a'.

let notes = ['c', 'd', 'e', 'f', 'g', 'a', 'b'];

let startIndex = 3; // start at 'f'

for (let i = startIndex; i < notes.length; i += 2) {
  let note = notes[i];
  console.log(note);
}

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

RN TypeScript is handling parameters with an implicit any type

My React Native (RN) application includes the following code snippet: handleTextChange = e => { this.setState({ value: e }) } I am using TypeScript (TS) and it's giving me a warning saying, "parameter 'e' implicitly has 'any&apos ...

Switching the displayed image depending on the JSON data received

As a beginner in javascript and jQuery, I am working on displaying JSON results in the browser. My goal is to generate dynamic HTML by incorporating the JSON data. Below is an example of the JSON structure: [{"JobName":"JobDoSomething","JobStatus":2,"JobS ...

Getting data from a wordpress database using javascript

After setting up a table named inspirationWall in my database with id and Visit_Count as INT, I inserted a row with id=1 and Visit_Count = 2. Now, attempting to fetch the Visit_Count value in WordPress and show it in an alert for testing purposes. I have ...

Leveraging jQuery or javascript to display json data in a table with multiple columns

My goal is to convert a JSON data into an HTML table that dynamically creates columns based on the content of the JSON. However, I am facing challenges in looping through the JSON and rendering multiple columns when necessary. The desired output for the e ...

Unexpected behavior occurs when React Hooks state changes are not properly passed as props

I am facing an issue with my React app that uses hooks. I want to pass down the state of slots as props to another component, but unfortunately, the other component always returns undefined and does not react to any changes in the slots state. Here is the ...

I am experiencing issues with my Discord.js bot not creating an invite link

Recently, I delved into discord.js but still have much to learn. While working on a bot, I encountered an issue with generating an invite link for the server. Instead of getting the link as expected, an error message popped up: D:\Discord Shield\ ...

Attempting to use jQuery AJAX to submit data without navigating away from the current webpage

Trying to implement the solution provided in this post where I am trying to send data to a PHP page and trigger an action, but unfortunately, it seems to just refresh the page without any visible outcome. Even after checking the network tab in the element ...

Interacting with the Chrome Password Storage Menu while leaving the mouse

Implemented an OnMouseLeave property in this menu to automatically close when user moves away from the menu space, which is working well. However, since it's a login form menu, clicking on input fields triggers Chrome's password manager to sugge ...

Picture navigation tool

Looking for a way to create a side navigating menu bar using HTML and CSS? The challenge is wanting the menu items to only appear after clicking on a small image positioned at the top left corner of the page, which happens to be my website logo. Does anyo ...

Is it possible that yuv.compressToJpeg does not support ByteArrayOutputStream as an input?

Trying to convert the byte array data received in onPreviewFrame to jpeg with the code below: ByteArrayOutputStream baos = new ByteArrayOutputStream(); YuvImage yuv = new YuvImage(data, ImageFormat.NV21, previewWidth, previewHeight, null); yuv.compressToJ ...

What is the proper way to implement React's Link component from an external npm package to avoid the error message stating, "you should not use link outside router"?

A custom NPM package has been developed to display an icon menu that can be used across multiple projects. Users have the flexibility to provide a 'route' prop to each icon, allowing them to act as links to different pages. Despite importing and ...

The libmagic library detects the MIME type of files as text/plain rather than text/javascript or

In my web project's interface, I am using libmagic to retrieve the MIME type of a file. Interestingly, I am encountering issues where css and js files are being identified as text/plain MIME type. When using Chromium, the following warnings are displ ...

An easy way to incorporate a fade-in effect for every word in a text

I am trying to make the text "Eat. Sleep. Repeat." slide up and fade in one word at a time. I have experimented with various methods like anime.js, keyframes, and adding css classes, but so far none of them have worked for me. Here is the code I currently ...

Ways to tally elements that have been dynamically loaded onto the webpage through AJAX requests

My page has a dynamic region that is continuously updated using jQuery's .ajax and .load methods. In order to submit the form, there need to be at least 3 of these 'regions', so I have to keep track of the number of DIVs with a specific cla ...

How to retrieve an object once it exits the viewport in JavaScript

I am seeking guidance on how to reset an object to its initial position (0) once it exits the browser window. Currently, I have an image that moves when you click on the up/down/left/right buttons, but it eventually extends beyond the browser window. Belo ...

Tips for dividing and locating the final index in Google Sheets

Is there a way to accomplish this in Google Sheets? tag_name A_B_C C A_B_C_D D I have been using the following formula: =INDEX(SPLIT(B2, "__"), 0, 3) My goal is to automatically select the last index of the values returned by the split fu ...

When conducting a click + drag mouse action, Internet Explorer may experience freezing. What steps can be taken to identify the root cause of this issue

Currently, I am in the process of developing a JavaScript application designed for generating simple diagrams. However, I have encountered some performance issues specifically in Internet Explorer version 8. This application allows users to draw lines on ...

In need of styling text using CSS?

Despite setting the CSS to .text { word-wrap : break-word; max-width: 100px}, the text is not wrapping as expected. It is still displaying in a single line. I am anticipating that the large text should wrap onto the next lines. ...

What could be the reason for the ReferenceError that is being thrown in this code, indicating that '

let number = 1; console.log(number); Feel free to execute this basic code snippet. You may encounter an issue: ReferenceError: test is not defined, even though the variable was declared. What could be causing this unexpected behavior? ...

Encountering a CastError in Mongoose validation where the value fails to cast to undefined

I encountered a forbidden message while attempting to save data into the database. CastError: Cast to undefined failed for value [ {"product":{"supplierId":{"undefined":"rfytr"}}}, {"product":{"supplierId":{"$empty":"rfytr"}}} ] at path "condition" ...