Adding Data to Array

Having an issue populating an array based on another array where pushing a value onto a specific index seems to populate all indexes.

Code

import { Component, VERSION } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  name = 'Angular ' + VERSION.major;
  public matrix: number[] = [
    // Array values here
  ];
  public matrixColumns: number[][] = [];
  public expectedMatrixColumns: number[][] = [
    // Nested arrays here
  ];
  public numberofColumns: number = 9;
  columnStartIndex: number = 0;

  constructor() {
    this.createColumnMatrix();
  }

  createColumnMatrix() {
    // Logic for creating column matrix here
  }
}

Demo Project

JavaScript version:

class AppComponent {
  matrix = [
    // Array values here
  ];
  matrixColumns = [];
  expectedMatrixColumns = [
    // Nested arrays here
  ];
  numberofColumns = 9;
  columnStartIndex = 0;

  constructor() {
    this.createColumnMatrix();
  }

  createColumnMatrix() {
    // Logic for creating column matrix here
  }
}

let component = new AppComponent();
for (let row of component.matrixColumns) {
    console.log(JSON.stringify(row));
}

Problem

Issue lies within this line:

this.matrixColumns[columnIndex].push(this.matrix[matrixIndex]);

The first value in the 'matrix' array is being pushed into every index in 'matrixColumns' instead of following the expected output pattern.

Expected output

// Expected output representation here

Actual output

// Actual output representation here

Answer №1

Here is an example of how you can achieve this:

const createMatrix = (data, columns) => data.reduce((result, d, i) => {
  const row = i % columns
  const rowData = [...(result[row] || []), d]
  result[row] = rowData
  return result
}, [])

const numbers = [
    1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
    23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41,
    42, 43, 44, 45,
  ];
  
const matrix = createMatrix(numbers, 9)

console.log(matrix)

Answer №2

For a proper representation, it is recommended to utilize two dimensions in the following manner:

this.multiDimensionalArray[columnIndex][matrixIndex].push(this.originalArray[columnIndex][matrixIndex]);

Answer №3

The issue lies in the fact that there is only a single columnsMatrix array being used. By repeatedly pushing its reference to this.matrixColumns, multiple references to the same array are created. Therefore, whether you push to this.matrixColumns[0] or this.matrixColumns[1], it results in pushing to the identical array.

To resolve this, a new array should be pushed onto this.matrixColumns with each call of push.

Instead of:

this.matrixColumns.push(columnsMatrix);

use:

this.matrixColumns.push([]);

Code Modification

Though not directly related to your query, you can modify the code as follows:

this.matrixColumns = Array.from({length: this.numberofColumns}, (_, i) =>
    Array.from({length: numberRows}, (_, j) => matrix[i + j*numberRows])
);

let matrix = [
    1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
    23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41,
    42, 43, 44, 45,
];
let numberofColumns = 9;
let numberofRows = Math.ceil(matrix.length / numberofColumns);
// logic
let matrixColumns = Array.from({length: numberofColumns}, (_, i) =>
    Array.from({length: numberofRows}, (_, j) => matrix[i + j*numberofRows])
);
// display
for (const row of matrixColumns) console.log(JSON.stringify(row));

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

Having trouble getting my Angular project up and running - facing issues with dependency tree resolution (ERESOLVE)

Currently, I am in the process of following an Angular tutorial and I wanted to run a project created by the instructor. To achieve this, I referred to the steps outlined in the 'how-to-use' file: How to use Begin by running "npm install" within ...

Ways to conceal a div element when the JSON data does not contain a value

If the value in "desc" is empty, then hide <div24> and <popup-desc>. html <div class="popup"> <div class="popup-top" style="background-color: '+e.features[0].properties.fill+';"> ...

Determine the presence of a value within an array

Imagine I have the following: $A = "1,2,3,4"; $B = "2"; What is the best way to check if $B is present in $A? UPDATE: In reality, $A is actually an array in my program: $A = array(1,2,3,4); $B = "2"; ...

Expanding Input Options Based on Dropdown Selections (PHP and JavaScript)

I am looking to dynamically add new input fields based on the option value selected from a dropdown menu. Here is an example of what the dropdown looks like: <form action="#" method="post"> <select name="job" id=& ...

Failed to convert the value "hello" to an ObjectId (string type) for the _id path in the product model

i am currently using node, express, and mongoose with a local mongodb database. all of my routes are functioning correctly except for the last one /hello, which is giving me this error: { "stringValue": "\"hello\"&qu ...

React fails to render within an Electron application

I've been attempting to execute some of the basic React examples within an Electron App, but I'm encountering an issue where nothing is displaying, despite the absence of any errors. Below is a snippet of the code: <!DOCTYPE html> <htm ...

What is the correct way to interpret a JSON file using TypeScript?

Encountering Error Error TS2732: Cannot locate module '../service-account.json'. It is suggested to use the '--resolveJsonModule' flag when importing a module with a '.json' extension. import serviceAccountPlay from '../ ...

The 'data-intro' property cannot be bound to the button element as it is not recognized as a valid property

I've been using the intro.js library in Angular 8 and so far everything has been working smoothly. However, I've hit a roadblock on this particular step. I'm struggling to bind a value in the data-intro attribute of this button tag. The text ...

Display a PDF file within an IFrame using JavaScript and then print it

Why is it so challenging to achieve? I've dedicated 48 hours to research this, yet it seems impossible! Although recent Chrome versions allow the parent window to access PDFs in iframes, both FF and IE prevent any interaction with the iframe that dis ...

`Why won't the checkbox uncheck when the dropdown is changed in jQuery?`

I have a roster of users, each with a unique checkbox for selection. When I adjust the dropdown menu, a new group of users is chosen and marked as selected. However, I am struggling to uncheck the previously selected checkboxes based on the last dropdown c ...

Dividing HTML and JavaScript using Vue

Is there a way to separate HTML from data/methods in VueJS to avoid having one long file with both? I tried moving the contents of my <script> section into a new file called "methods.js" and importing it using: <script src="methods.js"> Note ...

How can you automate the process of skipping a protractor test?

Is there a way to skip protractor test cases based on certain conditions being true or false? I tried using pending('skipped'); expect(true).toBe(true); But it is marked as failed. Update I found a way to add test cases to "Pen ...

What is the best way to package numpy array data?

My goal is to create a custom class that extends the base type of numpy array, class CustomArray(numpy.ndarray): @classmethod def init_from_data(cls, ...): cls(numpy.empty(...)) However, I encountered an issue where multi-dimensional array types ...

Angular2's ErrorHandler can cause code to malfunction when an error occurs

import { Injectable, ErrorHandler, Inject, Injector } from '@angular/core'; import { MessengerService } from '../services'; import { MessageTypeEnum } from '../../shared'; @Injectable() export class AppErrorHandler extends Er ...

Initiating the process of loading a texture atlas using PIXI Js and parcel bundler

I've recently started working with JS programming and pixi JS. I'm attempting to load a texture atlas from a json file following this tutorial module: https://github.com/kittykatattack/learningPixi#spriteproperties For my setup, I am using types ...

How can I resolve the issue of event listeners in a for loop executing concurrently instead of sequentially?

Being new to JavaScript, I am faced with a challenge that I'm trying to overcome. The following example illustrates the issue I'm struggling with. for (let i = 0; i < 3; i++) { test(); console.log("2"); } function test() { documen ...

Seeking a light-weight, text-rich editor specifically designed for use on our enterprise website. This editor should be even lighter than TinyMCE

I am in search of a lightweight text editor for an enterprise website, lighter than tinymce with basic buttons for the comment form. It is imperative that the editor also functions properly in IE6. So far, I have tried cleditor 15KB, but it has an issue in ...

PHP loop is not correctly accumulating all values in an array

Here is a script that I created: $alleTijden = array("ma_v" => $_POST['maandag_van'], "ma_t" => $_POST['maandag_tot'], "di_v" => $_POST['dinsdag_van'], "di_ ...

When browserify is utilized, the error "function is not defined" may show up as an Un

Exploring an example at and attempting a function call as shown below: My HTML code is: <!DOCTYPE html> <html> <head> <title>Testing Browserify</title> <script src="bundle.js"></script> </head> <body& ...

The reason for the undefined socket.id in the browser is due to a potential

When using console.log(socket), I am able to see a socket object in Firebug. Within this object, there is a property called id and I can view the value of this id. However, when I try to access it directly with console.log(socket.id), the result is undefin ...