An effective method for transforming a one-dimensional array into a matrix

My code involves an array that contains subarrays with x-coordinates, y-coordinates, and values representing a matrix:

// [x,y,value]
var arr = [
[1,2,0.01],
[1,3,0.02],
[1,4,0.05],
[1,5,0.03],
[2,3,0.04],
[2,4,0.02],
[2,5,0.01],
[3,4,0.06],
[3,5,0.05],
[4,5,0.07],
]

I also have a 2D array ("matrix") of dimensions x_max X x_max filled with zeroes. I'm attempting to efficiently populate this matrix using the following method:

// assuming 'matrix' is already defined and zero-filled

function constructMatrix(){
    for(var i in arr){
        var y = arr[i][0];
        var x = arr[i][1];
        var val = arr[i][2];
        matrix[y][x] = val;
    }
}

However, my resulting matrix has unique column values but duplicate values across rows. Can you help me identify where my logic might be flawed?

The expected output should resemble the following:

var matrix = [
[0.01,0.02,0.05,0.03],
[0,0.04,0.02,0.01],
[0,0,0.06,0.05],
[0,0,0,0.07],
]

Answer №1

Here is a way to achieve this:

var arr = [
    [1, 2, 0.01], [1, 3, 0.02], [1, 4, 0.05], [1, 5, 0.03],
    [2, 3, 0.04], [2, 4, 0.02], [2, 5, 0.01], [3, 4, 0.06],
    [3, 5, 0.05], [4, 5, 0.07]
];

// Determine the total number of rows and columns
// Add 1 because (x = 5) == (index 6)    // Indexes start at 0
var rows = arr.reduce((x,y) => Math.max(x, y[0]), 0) + 1;
var columns = arr.reduce((x,y) => Math.max(x, y[1]), 0) + 1;

// Create an empty matrix 
var matrix = [...Array(rows)].map(() => Array(columns).fill(0));

// Iterate over the points
arr.forEach(function(point) {
    var x = point[0];
    var y = point[1];
    var val = point[2];
    matrix[x][y] = val;
});

// Display the result
console.log(  JSON.stringify(matrix, 0, 2)  );
.as-console-wrapper {
  max-height: 100%!important;
}

Answer №2

If you are referring to the point (1,2) as the first column and second row in a grid, then the correct assignment would be:

matrix[y - 1][x - 1] = val

This adjustment accounts for the fact that coordinates begin at 0,0 and go up to 4,4 on a 5x5 matrix.

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

The issue with PHP array not functioning properly when used alongside a while loop

My PHP code is giving me an error message when I try to display information in the browser: Notice: Array to string conversion in. Can someone help me with this? I need to display this information from a function without creating a new one for every requ ...

Do not include any null or empty objects when assigning to an array in Mongoose

When using mongoose's find() or findOne() methods, the returned value will be [] and null, respectively, if the where conditions are not met. This can cause issues when assigning these values to an array. Currently, I am filtering out the null values ...

Discover all NestJS elements sorted by category

I am currently working with an entity called BookEntity: @Entity() export class BookEntity { @PrimaryGeneratedColumn() @Generated("increment") public id: number @CreateDateColumn() public createdAt: Date @Column() publ ...

Add a click event listener to the body element using a button click, without causing it to trigger

What is the current situation: A button is clicked by the user The menu opens (list items display = block) The function to close the menu is connected to the <body> The function to close the menu is immediately triggered, causing the menu to close ...

What is the best way to assign a percentage width based on a variable in jQuery?

Is there a way to assign a dynamic width value to an element? Here is the code I am using: $(".menu_list_item").css({ width: width + "%" }); Unfortunately, this doesn't appear to be functioning correctly. If anyo ...

Is it possible to submit a Framer.js prototype to be listed on the App Store?

Here's a quirky question for you... I have an idea for an iOS app art project that involves UI elements moving around on the screen. I know I could easily accomplish this in Framer, but I'm curious - is it feasible to transfer a Framer.js proto ...

Async/Await mishap

Could someone please explain why the code below is printing a blank result? I was expecting it to print "done" since I thought the await keyword would make the program wait for the promise to be resolved. Appreciate any help provided! let message = &apos ...

Why is it that PHP is used to retrieve the database value, JavaScript increments it, and AJAX saves it back to the database, yet it resets to 0.0 upon page refresh?

I am in the process of creating a page for setting temperature targets. The form allows users to adjust the target temperature by increments of 0.5 using JavaScript buttons. Once the user is satisfied with the new target, they can click 'set' whi ...

Calculating the distance matrix for a matrix with dimensions of 100,000 by 100,000 using R

I am facing a challenge with a vector A that has a size of 100k+. My goal is to calculate the distance between each element of this vector with every other element. I have been attempting to tackle this issue in R by utilizing its built-in adist function a ...

Generating hierarchical JSON data with PHP and MySQL

Currently, I am facing an issue with formatting an SQL Query's results in JSON format using json_encode(). I need help in achieving my desired data structure. Below is the PHP code <?php function data() { // SQL query to retrieve run distanc ...

The application runs smoothly during development, but encounters issues once deployed on Heroku

I am encountering an issue while deploying my app on Heroku. The deployment process goes smoothly, but when I try to open the app, I receive the following error message: Application error An error occurred in the application and your page could not be ser ...

Troubleshooting: The issue of Vue JS not successfully navigating between web

After countless attempts, I am still struggling to get my Firebase login function to appropriately switch the component upon signing in. I urgently need assistance with configuring my router to seamlessly transition to the next page once the sign-in proces ...

What could be the reason for encountering a TypeError while attaching event listeners using a for loop?

When attempting to add a "click" event listener to a single element, it functions correctly: var blog1 = document.getElementById("b1"); blog1.addEventListener("click", function(){ window.location.href="blog1.html"; }); However, when I try to use a for l ...

A guide on Implementing PastBack Functionality with AJAX Responses

When I make a GET request for an HTML page, I come across the following element: <a id="ctl00_cphRoblox_ClaimOwnershipButton" href="javascript:__doPostBack('ctl00$cphRoblox$ClaimOwnershipButton','')">Claim Ownership</a> My ...

Execute AJAX function following the completion of table loading from PHP in Ajax

I'm currently working on a shopping cart feature that involves calculating certain figures based on table values. The process involves loading the table using AJAX and PHP, which is functioning properly. However, I'm facing an issue where I nee ...

steps to remove the border of the select box in MUI component

i am struggling to disable the border on the select box and change the color of the label text when focused or blurred i have attempted it but have been unsuccessful i am not very skilled at Mui component customization this is the image that i desire ht ...

Preserve user-inputted text from jQuery within a div container

With the help of the knowledgeable individuals here, I successfully created a prototype to address an issue I had encountered. The problem involved using a textbox input with a password requirement to update an HTML element. Although everything is functio ...

Issue with Vue 3 where radio input remains unchecked after being clicked

I'm currently facing an issue with radio buttons for answers in my questions. Whenever I click on an answer, the radio input does not stay checked and I am unable to disable the other options. My front-end is developed using Vue 3 and the back-end wit ...

Navigating Angular on Internet ExplorerUnderstanding Angular's Compatibility

Having some trouble with an Angular app I'm developing. It displays perfectly on Chrome, but not at all on IE. Any tips on how to configure IE to show it correctly, or should I make changes to the app to ensure compatibility with IE? You can see how i ...

Tips for resizing images from Amazon S3 using Sharp

I'm encountering an issue while attempting to resize an uploaded image from S3 using @aws-sdk/v3 in a Node.js API. Initially, I retrieve the object (image) from S3 by following this example: https://github.com/awsdocs/aws-doc-sdk-examples/blob/master ...