Dynamic Array in JavaScript

5

I'm trying to dynamically generate an array arrays . For example:

check = function (title, filter) {
        if (checked.indexOf(title) !== -1) {
            checked[title].push(filter);
        } else {
            checked.push(title);
        }
};

check('arraypai','conteudo');
check('arraypai','outroconteudo');

So the result would be:

[
 arraypai[conteudo,outroconteudo]
]

and then ...

check('arraymae','coisa');
check('arraymae','outracoisa');

and the result would be:

[
 arraypai[conteudo, outroconteudo],
 arraymae[coisa, outracoisa]
]
    
asked by anonymous 11.11.2014 / 21:28

2 answers

3

If the question is "associate the name X with the array Y", then the best way to do this is to use an array dictionary (ie a simple object, whose keys are names and whose values are arrays):

var checked = {};

check = function (title, filter) {
        if (checked[title] !== undefined) { // Testa se a chave existe
            checked[title].push(filter);    // Adiciona um elemento no array
        } else {
            checked[title] = [filter];      // Se não existe, cria um array com um elemento
        }
};

check('arraypai','conteudo');
check('arraypai','outroconteudo');
check('arraymae','coisa');
check('arraymae','outracoisa');

document.getElementById("saida").innerHTML = JSON.stringify(checked) + "<br/>" +
  checked["arraypai"].join(", ") + "<br/>" +
  checked.arraymae.join(", ");
<span id="saida"></span>
    
11.11.2014 / 22:05
2

Basically everything you want to do with associative array can be done with objects.

To print, for example, you can iterate over the keys (attributes) of the object, as in the following example:

var checked = {};

var check = function (title, filter) {
    if (checked[title]) checked[title].push(filter);
    else checked[title] = [ filter ];
};

var compilar = function(){
    var str = "";
    for(var key in checked){
        str += key + "[" + checked[key].toString() + "];";
    }
    print(str + "<br />");
};

check('arraypai','conteudo');
check('arraypai','outroconteudo');
compilar();




// Função de comodidade para imprimir o resultado. Ignore-a :)
function print(source){
    var p = document.createElement("p");
    p.innerHTML = source;
    document.body.appendChild(p);
}
    
11.11.2014 / 22:05