Converting a one-dimensional array into a two-dimensional array in JavaScript explained

Below is the code snippet

const arrayColumn = (arr, n) => arr.map(x => x[n]);
const pcorr = (x, y) => {
  let sumX = 0,
    sumY = 0,
    sumXY = 0,
    sumX2 = 0,
    sumY2 = 0;
  const minLength = x.length = y.length = Math.min(x.length, y.length),
    reduce = (xi, idx) => {
      const yi = y[idx];
      sumX += xi;
      sumY += yi;
      sumXY += xi * yi;
      sumX2 += xi * xi;
      sumY2 += yi * yi;
    }
  x.forEach(reduce);
  return (minLength * sumXY - sumX * sumY) / Math.sqrt((minLength * sumX2 - sumX * sumX) * (minLength * sumY2 - sumY * sumY));
};

// Generating a Pearson correlation matrix
        var r = [[]];
        var r_temp = [];
        for (var i = 1; i <= _arrData[0].length; i++) {
          for (var j = 1; j <= _arrData[0].length; j++) {
            r_temp.push(pcorr(arrayColumn(_arrData,i-1),arrayColumn(_arrData,j-1)));
          }
        }
        
        var r_temp_length = r_temp.length;
        for (var i = 1; i <= _arrData[0].length; i++) {
          for (var j = 1; j <= _arrData[0].length; j++) {
            r[i - 1][j - 1] = r_temp[_arrData[0].length^2 - r_temp_length];
            r_temp_length = r_temp_length - 1;
          }
        }

_arrData represents data from a .csv file that has been read and formatted as a 43x4 matrix. The result of r_temp is shown below:

[1, 0.1001546791334383, -0.09722360940329312, -0.1119017933192886, 0.1001546791334383, 1, 0.19766088533723247, -0.03844791092325515, -0.09722360940329312, 0.19766088533723247, 1, -0.06161560854254137, -0.1119017933192886, -0.03844791092325515, -0.06161560854254137, 1]

The length of r_temp is 16.

The aim is to input the values from r_temp into r, creating a 4x4 Matrix.

An error occurs at this specific line when running the code:

r[i - 1][j - 1] = r_temp[_arrData[0].length^2 - r_temp_length];

The following error message is displayed: Uncaught TypeError: Cannot set property '0' of undefined.

Answer №1

let result = [];

...

for (let j = 1; j <= _arrData[0].length; j++) {
    result[j - 1] = [];

....

The correct initialization should be let result = []; instead of [[]].

A crucial line in your code is missing: result[i - 1] = [];

This creates the second array for result[i - 1].

Answer №2

Appreciate all of your help, it's finally working!

//initialize pearson correlation matrix
        var r = [];
        for (var i = 1; i <= _arrData[0].length; i++) {
          r[i - 1] = [];
        }
        var r_temp = [];
        for (var i = 1; i <= _arrData[0].length; i++) {
          for (var j = 1; j <= _arrData[0].length; j++) {
            r_temp.push(pcorr(arrayColumn(_arrData,i-1),arrayColumn(_arrData,j-1)));
          }
        }
        var r_temp_length = r_temp.length;
        for (var i = 1; i <= _arrData[0].length; i++) {
          for (var j = 1; j <= _arrData[0].length; j++) {
            r[i - 1][j - 1] = r_temp[Math.pow(_arrData[0].length,2) - r_temp_length];
            r_temp_length = r_temp_length - 1;
          }
        }

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

"Enhance Your Coding Experience with Visual Studio Code - TypeScript Definitions Catered

I am currently working on developing a basic web application using Node.js and Express. I have successfully installed both definitions using tsd following the steps outlined in this guide. When I run tsd query mongodb --action install, I do not encounter ...

How to implement a form in PHP that doesn't refresh the page upon submission

I am having an issue with this ajax code. I know it works, but for some reason it's not submitting. <script type="text/javascript"> $(function(){ $('input[type=submit]').click(function(){ $.ajax({ type: "POST", ...

Tips for properly removing Bootstrap 4 tooltips when deleting their corresponding DOM element using html()

In my Bootstrap 4 project, I've implemented a live search box that displays results with tooltips for longer descriptions. I've written jQuery scripts to hide the search results and their parent div when certain events occur, like clearing the se ...

No departure animation employed - Polymer

I am working on a project that involves animating a paper-icon-button with spin and opacity effects when hovering over an image using the on-mouseenter and on-mouseleave events. Everything works smoothly when hovering over the image, but I am facing an is ...

Ensuring that an added row remains at the bottom of a table composed of rows generated dynamically by utilizing the .detach() method

I need to ensure that the "subtot" row is always appended as the last row in the table. When dynamically adding rows, the "subtot" row appears as the last row the first time, but does not stay at the bottom when more rows are added. Even though I want the ...

When using the jQuery ajax function to validate a form, it is important to note that the $_POST variables

I have an HTML form along with a jQuery function for form validation. After submitting the form values to my PHP files, I notice that the $_POST variable is not being set. What could be causing this issue? <form id="signup" class="dialog-form" action= ...

Issues arising from the implementation of AJAX forms

Currently, I am working with Ruby on Rails 3.1.1 and using the jquery-rails 1.0.16 gem in my project. The issue I am facing involves utilizing a form with :remote => true. Within my view file, the form snippet looks like this: <%= form_for(@user, : ...

Send binary information using Prototype Ajax request

Currently, I am utilizing Prototype to send a POST request, and within the postdata are numerous fields. One of these fields contains binary data from a file, such as an Excel spreadsheet chosen by the user for upload. To retrieve the contents of the file ...

angular 2 checkbox for selecting multiple items at once

Issue I have been searching for solutions to my problem with no luck. I have a table containing multiple rows, each row having a checkbox. I am trying to implement a "select all" and "deselect all" functionality for these checkboxes. Below is an example o ...

What is the optimal location for storing component fetch logic?

When should I make a REST request to retrieve data for a Vue component called Page, specifically for the properties title and content? Also, where is the best place to handle this logic? Currently, I am trying to fetch the data on the component's rea ...

Revamping array elements in React

Once I added an element to the array, I needed to update this array by doubling all elements except for the one that was just added. Despite trying setArray([]) before retrieving the array from the database, it didn't seem to work... const [array, se ...

An External Force is Disrupting My Jquery

Something seems off because everything was working perfectly fine until the FallingLeavesChristmas.min.js file stopped activating on this specific page. I initially thought it was an issue with the JavaScript itself, but that doesn't seem to be the ca ...

Deselect a checkbox by selecting a radio button with just Javascript code

Hey there! I'm currently delving into the world of pure JavaScript and could really use some guidance on a particular issue. Here's what I'm aiming to accomplish: I'd like to design a checkbox that triggers the opening of a window whe ...

The next button will only activate once all input forms have been completed in multiple forms

In the JavaScript code: var current_fs, next_fs, previous_fs; //fieldsets var left, opacity, scale; //fieldset properties that will be animated var animating; //flag to prevent rapid glitches from multi-clicking $(".next").click(function(){ if(animati ...

Having trouble processing the Firebase snapshot with Node.js

I have a question regarding a snapshot; ref.orderByChild("index").equalTo(currentIndex).once("value", function(snapshot) {}) After printing the snapshot with ; console.log(snapshot.val()); This is the output that gets printed; {'-LBHEpgffPTQnxWIT ...

Working with an array of object in Vuex for form handling

Looking to make updates to a vuex store that includes an array of objects: Users have a combobox for making selections, which then updates a property of the object in the database. However, every time I choose an item from the autocomplete (combobox) I e ...

Trying out asynchronous testing using Mocha and Sinonjs for the first time

In my current project, I am utilizing a custom micro framework developed by our team, where we make use of Mongoose. To handle the mongoose object, we have implemented a modelfactory that provides us with a corresponding model based on the mongoose name o ...

JQuery - stylish vertical accordion navigation menu

I'm currently working on a vertical accordion-style sidebar navigation system. Everything seems to be functioning properly, but I've encountered some issues with the icons that I'm using from Twitter Bootstrap 3. You can view the code on th ...

Tips for alternating the color of <li> or <tr> elements consecutively

Looking to alternate the background color of li or tr elements consecutively. Please note: A static class will not work as I need to call this in a while loop. The desired output should look like: <li>line1</li> //white background <li> ...

Include an element in a secondary list based on its position in the initial list

Having 2 lists presents a challenge. An Angular service is utilized with a splice-based method to remove items from the first list (named "items") according to their index through a ng-click action. service.removeItem = function (itemIndex) { items ...