Array list in multidimensional array

1

I have this loop:

aaff = [];contador_selecionados=0;
$(' .values .layout .acf-input').children('').each(function(index,element){
contador_selecionados++;
aaff.push( element.value);
console.log(contador_selecionados);
 }); 
console.log(aaff);

That returns:

Array(9) [ "calças", "XXS", "16", "fita", "M", "13", "calças", "XXS", "1" ]

Now, I need to break it down to 3 like:

[calças, xxs,16]
[Fita , M,13]
[Calça, xxs,1]

How can I do this?

    
asked by anonymous 15.10.2018 / 19:25

2 answers

2

Try this:

aaff = [ "calças", "XXS", "16", "fita", "M", "13", "calças", "XXS", "1" ];

var ret = [];
for (var i = 0; i < aaff.length; i += 3) {
    ret.push([aaff[i], aaff[i + 1], aaff[i + 2]]);
}

console.log(ret);

Or this:

aaff = [ "calças1", "XXS", "16", "fita", "M", "13", "calças2", "XXS", "1" ];

var ret = {};
for (var i = 0; i < aaff.length; i += 3) {
    ret[aaff[i]] = {tipo: aaff[i + 1], tamanho: aaff[i + 2]};
}

console.log(ret);
    
15.10.2018 / 19:32
1

With the reduce function of JavaScript you get this result.

See the live example here: link

As you explained, your data set is 3 items within the list. That is, every 3 items in the original list you put a new item in the new list.

// Dados recebidos.
const dados = [ "calças", "XXS", "16", "fita", "M", "13", "calças", "XXS", "1" ];

// Total de itens que compõem um conjunto
const conjunto = 3;

//Nova lista
const dadosMapeados = dados.reduce((val, cur) => { 
   if (val.length === 0 || val[val.length - 1].length === conjunto) val.push([]); 
   val[val.length - 1].push(cur); 
   return val; 
}, []);

The result for dadosMapeados will be this:

[
    ["calças", "XXS", "16"],
    ["fita", "M", "13"],
    ["calças", "XXS", "1"]
]

If you need to use JSON instead of ARRAY , use the map JavaScript function on top of the result. But you need to ensure that the array has enough elements or make a check by switching item[0] to item.length > 0 ? item[0] : null in the example below.

dadosMapeados = dadosMapeados.map(item => { return { 
    nome: item[0], 
    tipo: item[1], 
    tamanho: item[2]
}});

Now, the result for dadosMapeados will be this:

{
    {nome: "calças", tipo: "XXS", tamanho: "16"},
    {nome: "fita", tipo: "M", tamanho: "13"},
    {nome: "calças", tipo: "XXS", tamanho: "1"}
}
    
16.10.2018 / 20:58