Tengo una matriz con datos que me gustaría ordenar/mover a tres matrices diferentes. Los datos en la matriz se ven así: data_array["101","08:00","45","102","08:00","46","102","08:00","47","101","08:01","46","102","08:01","45"] ... El primer dato es un id, el segundo un sello de tiempo y el tercero un temperatura y luego vuelve a empezar. ¿Cómo puedo hacer esto?
Este es mi intento:
var id = [] var time_stamp = [] var temperature = [] data_array = ["101","08:00","45","102","08:00","46","102","08:00","47","101","08:01","46","102","08:01","45"] int counter = 1; foreach(var item in data_array) { if(counter == 1) { vlan_id.push(item); counter++; } else if (counter == 2) { time_stamp.push(item); counter++; } else if (counter == 3) { temperature.push(item); counter = 1; } }Puede tomar un índice e incrementar para cada parte.
const id = [], time_stamp = [], temperature = [], data = ["101", "08:00", "45", "102", "08:00", "46", "102", "08:00", "47", "101", "08:01", "46", "102", "08:01", "45"]; let i = 0; while (i < data.length) { id.push(data[i++]); time_stamp.push(data[i++]); temperature.push(data[i++]); } console.log(...id); console.log(...time_stamp); console.log(...temperature);Un enfoque ligeramente diferente
const id = [], time_stamp = [], temperature = [], data = ["101", "08:00", "45", "102", "08:00", "46", "102", "08:00", "47", "101", "08:01", "46", "102", "08:01", "45"], targets = [id, time_stamp, temperature]; let i = 0; while (i < data.length) { targets[i % targets.length].push(data[i++]); } console.log(...id); console.log(...time_stamp); console.log(...temperature);Más o menos lo que estás haciendo es correcto.
var id = [] var time_stamp = [] var temperature = [] const data_array = ["101","08:00","45","102","08:00","46","102","08:00","47","101","08:01","46","102","08:01","45"] let counter = 1; for(const d of data_array) { if(counter === 1) { id.push(d); } else if(counter === 2) { time_stamp.push(d); } else if(counter === 3) { temperature.push(d); } counter++; if(counter > 3) counter = 1; }Una solución potencial usando .reduce() .
Fragmento de código
const data_array = ["101", "08:00", "45", "102", "08:00", "46", "102", "08:00", "47", "101", "08:01", "46", "102", "08:01", "45"]; const {id, time_stamp, temperature} = data_array.reduce( (acc, itm, idx) => ({ // iterate over array using ".reduce()" ...acc, ...( // based on "idx" add "itm" to "id", "time_stamp" or "temperature" arrays idx % 3 === 0 ? { id: acc.id.concat([itm]) } : idx % 3 === 1 ? { time_stamp: acc.time_stamp.concat([itm])} : { temperature: acc.temperature.concat([itm])} ) }), // initialize 'acc' with below object {id: [], time_stamp: [], temperature: []} ); console.log( 'id: ', ...id, '\ntime_stamp: ', ...time_stamp, '\ntemperature: ', ...temperature );Explicación
Los comentarios en línea describen los aspectos significativos de la solución.