Doubt in array n rows x 3 columns

Asked

Viewed 2,855 times

0

I am in doubt in JS matrix, where I need to include a value within the first position of each item consecutively. JS Code:

m_aluno = new Array ();   
    if(w_cont < w_alun)//w_cont é para não passar do valor informado and w_alun é o valor informado;
    {
        for(a=0; a < w_alun; a++)
            for(c=0; c < w_cole; c++)
                for(s=0; s < w_sala; s++)
                    for(m=0; m < w_mate; m++){
                        m_aluno[a][c]= w_nome;
                        m_aluno[a][s]= w_nome;
                        m_aluno[a][m]= w_nome;
                    }
                    w_cont++;   
    }

That is: I want to include in the first position of each the name typed! The name is entered in w_nome;

Basically I would like to add at position 0 of the array the name inserted but apparently in JS is not possible, because JS does not support; because its structure would be:

m_aluno[c][s][m]= "nome";
  • 5

    I think you’ll have to explain a little better the structure of this array, because either you’re missing index (and it’s not 5x3), or you’re using loops for something that should be static (or both). It would have to describe an example of how the array should be at the end, for two students, for example?

  • 1

    I think the explanation gave anyway, we don’t know how many w_cole each student can have, etc. Better to give a practical example of the filled array, and not of what you’re imagining (help us help you). It would be good to explain where the other information comes from, because you can’t tell what w_cole is (if it’s an array, if it’s a number, if it’s a string)

  • 2

    Even after the edition, it has not improved much... Can you name the oxen? For example: what will this matrix contain, exactly? Names, notes, registration data? How it is structured (what the rows and columns represent)?

  • Examples with concrete data would help more than theories. Theories are based on how you see the problem. The concrete data would help to present a solution to the problem, regardless of how you are seeing it. Look for an example of exactly what you want (and explain what each of the data is).

  • Everything indicates that you only need a loop, and within each position of the array an object (and no more arrays). But I would need to post the information that Bacco and Rui asked for so that we can affirm anything.

  • The question title does not invite anyone reading the main page to open the question and see what the problem is. It is the typical example of poor title, try to get into it too.

Show 1 more comment

1 answer

3


An array, in Javascript, can be simulated through nested arrays.

What is called line or spine is merely symbolic and abstract; I specifically like to think of the lines as being the positions of the parent Array:

var minhaMatriz = [
    linha0, // ainda indefinida!
    linha1 // ainda indefinida!
];

But each line (so we get one matrix) is an Array itself, where each position represents a cell, whose definition is the crossing of a row with a column. Thus, we can say that "the rows have the columns" (according to the way I like to think):

var minhaMatriz = [
    [ "L0 C0", "L0 C1", "L0 C2" ],
    [ "L1 C0", "L1 C1", "L1 C2" ]
];

With this, we will have a 2x3 matrix, that is, 2 rows by 3 columns.

Since Javascript is a language with dynamic typing, in addition to the content (value) of each cell being fully open at your choice, we don’t even need to define the type; just iterate over the matrix to set or modify the value of each column.

To iterate over the matrix, just iterate over the calls lines, and, within this iteration, also iterate on the calls columns. In the example below, the index i denotes the current line, and the index j denotes the current column:

// Troca o valor de todas as células para o inteiro 0:
for(var i = 0; i < minhaMatriz.length; i++){        // Para cada linha (índice "i")
    for(var j = 0; j < minhaMatriz[i].length; j++){ // Para cada coluna (índice "j")
        minhaMatriz[i][j] = 0;                      // Troca o valor da célula da linha "i", coluna "j".
    }
}

So, to only go through the first column of an array, we only need a single loop:

// Troca o valor de cada célula da primeira coluna para 0:
for(var i = 0; i < minhaMatriz.length; i++){
    minhaMatriz[i][0] = 0; // Troca o valor da célula da linha "i", coluna 0.
}

Variable size

So far, we have created a 2D matrix (two-dimensional matrix, that is, it has the dimensions height, which corresponds to the number of lines, and width, which corresponds to the number of columns) conceptually static, in the sense that it has already been declared with the data.

It could also have been declared without any line:

var minhaMatriz = [];

Regardless of how it was stated, however, we can both edit the data inside it (as already demonstrated), we can also apply operations on the size of it.

Line insertion

As stated before, the matrix is an Array of lines, and the lines are programmed as Arrays of cells. Thus, to add lines, just insert a new Array of cells in the Array, through the native method push(elemento) array. Obs.: this method always adds the "elemento" at the end Array, so in the example below, the new line will be the last:

minhaMatriz.push(
    [ "Nova linha C0", "Nova linha C1", "Nova linha C2" ]
);

Removing and/or inserting lines in arbitrary indexes

Similarly, there is a native function that removes* elements from the Array: splice(indice, quantidade). Obs.: this method removes from the position denoted by "indice", a number "quantidade" elements. To remove the last element, for example, we can do:

// Remove, da última posição da matriz (minhaMatriz.length - 1), um (1) único elemento:
minhaMatriz.splice(minhaMatriz.length - 1, 1);
  • In fact, the splice() also adds elements! It can be used to insert lines into our matrix at arbitrary positions! Example:

    minhaMatriz.splice(1, 0, [ "C0", "C1", "C2" ] );


Interactive example

To summarize, I present a small program that inserts and removes lines in arbitrary positions. (It will probably only work on the latest browsers!)

// Declaramos uma matriz com pelo menos uma linha, para que nosso exemplo saiba quantas
// colunas pretendemos utilizar:
var m = [
    [ "Olá", "Stack Overflow", "em Português!" ]
];

// Localizamos os elementos declarados no HTML com os quais interagiremos:
var inputIdx = document.getElementById("inputIdx");
var botaoAdd = document.getElementById("botaoAdd");
var botaoRem = document.getElementById("botaoRem");
var pTabelas = document.getElementById("pTabelas");

// Criamos uma caixa para cada coluna (elementos dinâmicos, declarados 'on the run'):
var inputs = [];
for(var i = 0; i < m[0].length; i++){
    inputs.push(_new("input", document.getElementById("spanInputs")));
}

_print(); // Mostramos como está nossa tabela inicialmente.



// Ao clicar o botão de adicionar, criamos uma nova linha no índice específicado:
botaoAdd.addEventListener("click", function(){
    var novaLinha = [];
    for(var i in inputs) novaLinha.push(inputs[i].value);
    
    m.splice(+inputIdx.value, 0, novaLinha);
    // OBS.: o "+" aqui é uma forma rápida de converter para inteiro!
    
    _print(); // Mostra como ficou nossa matriz.
});



// Ao clicar o botão de remover, removemos a linha do índice especificado:
botaoRem.addEventListener("click", function(){
    m.splice(+inputIdx.value, 1);
    // OBS.: o "+" aqui é uma forma rápida de converter para inteiro!
    
    _print(); // Mostra como ficou nossa matriz.
});



// Imprime a matriz como uma tabela HTML dinâmica:
function _print(){
    // Retira a visualização antiga:
    while(pTabelas.firstChild) pTabelas.removeChild(pTabelas.firstChild);
    
    var table = _new("table", pTabelas);
    
    // Cria a linha de título:
    var titleRow = _new("tr", table);
    _new("th", titleRow);
    for(var j = 0; j < m[0].length; j++){
        var titleCell = _new("th", titleRow);
        titleCell.innerHTML = j;
    }
    
    // Para cada linha da matriz, cria uma linha na tabela HTML:
    for(var i = 0; i < m.length; i++){
        var row = _new("tr", table);
        
        // Em cada linha, insere uma coluna de título:
        var titleCell = _new("th", row);
        titleCell.innerHTML = i;
        
        // Para cada coluna da matriz, insere uma coluna HTML:
        for(var j = 0; j < m[i].length; j++){
            var cell = _new("td", row);
            cell.innerHTML = m[i][j];
        }
    }
}







// Função de comodidade para criar e exibir elementos de maneira dinâmica. IGNORE-A! :)
function _new(tag,pai){
    var el = document.createElement(tag); // Cria elemento pedido.
    pai.appendChild(el);                  // Insere o elemento no pai.
    return el;                            // Retorna o elemento para manipulações posteriores.
}
table { border-collapse: collapse; }
td, th { border: 1px solid black; padding: 2px 15px; }
input { width: 75px; }
<p>
    Linha a inserir: <span id="spanInputs"></span>
    <br />
</p>
<p>
    Índice: <input id="inputIdx" type="number" value="0" />
    <button id="botaoAdd">Adicionar no índice</button>
    <button id="botaoRem">Remover do índice</button>
    <br />
</p>
<p id="pTabelas"></p>


Completion

To make the matrix N x 3 (N rows of 3 columns) you need, just think that the column indexed by j=0 is the college, the column j=1 is the room, and the column j=2 is what you call mate (subject / discipline?).

Thus, it makes no sense to increase the number of matrix dimensions (for example, program it N x M x O x P). The problem must be more localized in the representation (modeling) of your business knowledge, than in the Javascript language itself.

If you need more help in JS, a first step is to always check the "class documentation"

  • 3

    Let’s hope it’s just that ;)

  • What I needed @Ruipimentel' was hard to explain but I managed to get to what I needed!

  • That is, to declare the matrix nx3 var minhaMatriz=[[,,]];

  • Comment if the answer matched what you needed!

  • The answer matched what I needed, but how should I ride n x 3? I couldn’t decipher how!

  • If the idea is to make the matrix size dynamic (and nay increase the number of dimensions), inserting and deleting elements, take a look at the new changes :D

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.