Multidimensional array list

Asked

Viewed 87 times

1

I have this bond:

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);

Returning:

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

Now, I need to divide it into 3 just like:

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

How can I do that?

  • Can make available the HTML of the page to inform what would be the best approach for your case?

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);

  • obg Victor, do you have any idea how I can name the array with pants {xxs,16}, Tape{m,13} ?

  • @I-amSam I don’t know if I understand what you want, but if what you want is a JSON where pants and ribbon are keys and xxs, 16 and m, 13 are values, so will not give because there would be two keys "pants".

  • that’s it , forgets that are two equal Keys , imagine that are pants 1 and trousers 2

  • 1

    @I-amSam Edited. Serves for what you wanted?

  • Perfect , Thank you Victor

1

With the function reduce from Javascript you get this result.

See the live example here: https://jsfiddle.net/ovqn2c6t/

From what you explained, your data set is 3 items within the list. That is, every 3 items in the original list you assemble 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 to 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 function map Javascript on top of the result. But you need to ensure that the array has enough elements or do a check by swapping item[0] for 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"}
}

Browser other questions tagged

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