Unleashing the power of JavaScript: A guide to dynamically generating nested arrays

Can you take a look at the code below and help me find the mistake?

function pair(str) {

  // Function to pair specific letters in a string

  for (var i = 0; i < str.length; i++) {

    // Check and pair letters based on certain conditions

    if (str[i] == 'G' && str[i - 1] != 'C') {
      str = str.slice(0, i) + 'C' + str.slice(i);
    } else if (str[i] == 'T' && str[i - 1] != 'A') {
      str = str.slice(0, i) + 'A' + str.slice(i);
    } else if (str[i] == 'C' && str[i + 1] != 'G') {
      str = str.slice(0, i + 1) + 'G' + str.slice(i + 1);
    } else if (str[i] == 'A' && str[i + 1] != 'T') {
      str = str.slice(0, i + 1) + 'T' + str.slice(i + 1);
    }
  }

  str = str.split('');

  var temp = [];
  for (var j = 0; j <= str.length / 2; j++) {
    temp.push([]);
    for (var k = 0; k < 2; k++) {
      temp[j].push(str.shift());
    }
  }
  return temp;

}

pair("TTGAG");

The expected output is [['A', 'T'], ['A', 'T'], ['C', 'G'], ['A', 'T'], ['C', 'G']]. However, the actual output is [['A', 'T'], ['A', 'T'], ['C', 'G']]. Can you spot the mistake?

Answer №1

It appears that the issue has been identified. Essentially, the key is to establish the limit for the outer for loop prior to its execution.

var limit = str.length / 2 -1;
for (var j = 0; j <= limit; j++) {
...

Alternatively,

var limit = str.length / 2;
for (var j = 0; j < limit; j ++) {
...

The rationale behind this is that with each shift operation in the inner loop, the size of the str array decreases by one. The j <= str.length /2 expression is assessed at the start of each loop, after two shifts have already occurred in the prior inner loop.

Initially, str.length / 2 == 5; temp == [['A', 'T']]

Subsequently, following two shift operations, str.length / 2 == 4; temp == [['A', 'T']['A','T']]

After two more shifts, str.length /2 == 3;

temp == [['A','T']['A','T']['C','G']]

Upon the final evaluation of the outer for loop condition, with str.length / 2 == 2, and j == 2, the loop concludes.

For more information on for loops, the MDN reference can be found here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for

Answer №2

If I understand correctly, you're facing the task of converting an input string like "TTGAG" into an array of [A,T] or [C,G].

Here is the approach I suggest:

// renamed pair function for clarity
// assuming genes == 'TTGAG'
function GeneStringToArray(genes){
    var geneSplit = genes.split(''); // [T,T,G,A,G]

    for(var i = 0; i < geneSplit.length; i += 1){
        geneSplit[i] = getGenePair(geneSplit[i]);      
    }

    return geneSplit; // output: [['A','T'],['A','T'],['C','G'],['A','T'],['C','G']]
}    


function getGenePair(gene) {
    // converting to lowercase for easy comparison
    gene = gene.toLowerCase();

    // Defining results
    var at = ['A', 'T'];
    var cg = ['C','G'];

    if(gene === 'a' || gene === 't'){
        return at;
    }

    if(gene === 'c' || gene === 'g'){
        return cg;
    }
}

I believe this solution provides a clear and readable way to address your issue.

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

Check if the page has been loaded using Jquery

Can anyone share a helpful strategy for initiating a function in JavaScript that only begins once the entire page has finished loading? ...

Refreshing a component in React when a prop changes

My understanding is that React components update when their props or state change. For example, I declare a variable like this: let percentage = { width: '10%', }; Then, I have a function using setInterval to upd ...

Submit a HTML form to a Telegram recipient

I am looking to send HTML form data, which includes input values and select options, to a telegram user. After some research, I discovered that I need to create a Telegram bot. I successfully created one using @botFather by following these steps: /newbot ...

Switch up your text display using JQuery and toggle between different texts

I have implemented a jQuery script to toggle the display of certain paragraphs when the "More" link is clicked. However, I am facing an issue where the link always displays "More" even after the content has been expanded. I want it to change to "Less" once ...

Display the information contained within an array in a table using React

I have two arrays: one named formData and the other state array. const [formData, setFormData] = useState([]); let ure = [{}] useEffect(() => { axios .get("/api/listUre") .then((res) => { console.log(res.data ...

Ways to extract single JSON entities from a consolidated JSON structure

I am facing a challenge with parsing multiple JSON objects within a single large JSON object. Currently, the entire JSON object is being stored as one entity, but I need to parse and store them separately in MongoDB. Below is the code snippet I am using. ...

Using window.open and appending a new feature to it

Below is the code found in my index.html file: <!DOCTYPE html> <html> <head> <script> function createDialogBox() { var dialogBox = window.open("in1.html"); dialogBox.nameBox= "my little box" } window.onload = createDialogBox; wind ...

Accurate representation of a JavaScript object using Node.js Express

I have a certain structure that I need to display on my JADE page, so I created a JSON-like object to store the data. This is how the JSON object looks like : var dataSet1 = { meta: { "name": "Some text", "minimum": mini_2, "ma ...

Using AngularJS to add external scripts to partials with ng-include

Why won't my main javascript files (located in index.html) work in the partials (such as page1.html)? For example, jQuery and syntax highlighting scripts are not functioning properly when I click on my menu items. HTML CODE: <div data-ng-controll ...

What is causing ngdocs to produce zero files?

I have created a basic project to experiment with grunt-ngdocs (https://www.npmjs.org/package/grunt-ngdocs). But, for some reason, when I attempt to generate documentation, it fails to recognize any comments. Why is this happening? Can someone offer assist ...

Steps for modifying an element in an array using Javascript

Currently, I am a beginner in the realm of JavaScript and I am trying to build a todo-style application. So far, I have successfully managed to create, display, and delete items from an array. However, I am facing challenges when it comes to editing these ...

When implementing dynamic routing in Next.js, an error occurs with TypeError: the 'id' parameter must be a string type. It is currently

I’m encountering a problem while creating dynamic pages in Next.js. I'm fetching data from Sanity and I believe my code is correct, but every time I attempt to load the page, I receive a type error - “the ‘id’ argument must be of type string. ...

Exploring the Magic of Class Variable Destructuring in React

Is there a simpler method to break down a prop object and assign them to variables of the same name in the class? I am familiar with ({ first: this.first, second: this.second, } = props) however, it can get complicated when dealing with numerous variable ...

Using jQuery to set the background-image on the body's after pseudo-element with CSS

I am currently utilizing body:after for setting the page wallpaper. body:after { background-image: url('assets/img/wallpapers/<?php echo $getWallpaperFile; ?>'); } CSS content: ' '; display: block; position: absolute; left: ...

What is the process for redirecting to a different URL when the button is clicked?"

I am trying to display Home.js at localhost/posts, but when the button is clicked, it displays information at the auth.js URL. How can I link the button so that if the login information is correct, it redirects to "localhost/posts" instead of rendering its ...

Checking the Ajax request with an if statement

$("#Submit").click(function(event){ event.preventDefault(); var th = '<tr><th>' + "Business" +'</th><th>' + "Address"+ '</th><th>'+ "Rating" + '</th><th>' + "Da ...

Preserving scroll position when updating a partial page template using Rails and AJAX

When I am utilizing long polling, I encounter an issue where every time I use AJAX to refresh a page partial inside a scrollable div, the contents automatically scroll to the top. Is there any way to load the partial while maintaining the current scroll ...

Is this filter selector in jQuery correct?

It appears to function correctly, but I am unsure if there is room for improvement. I aim to target any HTML element with a class of edit-text-NUM or edit-html-NUM and adjust its color. This is the code snippet I am currently utilizing... jQuery(document ...

Attempting to demonstrate how to handle a duplicate entry error within a MySQL database through the use of Express.js and React.js

I have developed a CRUD application that is functioning perfectly. Now, I am working on adding validation to it in order to notify users when they try to insert an entry that already exists in the database. This is what I have implemented so far: console ...

Troubleshooting Problems with Adjusting Left Margin Using JQuery

function adjust_width() { $('#cont').toggle(function(){ $('#cont').animate({marginLeft:'0%'}); },function(){ $('#cont').animate({marginLeft:'18.4%'}); }); } The code above is in ...