Mi entrada es const
:
input = [ ["A", "B", "C", "D"], ["a", "b", "c"], [1, 2, 3, 4, 5, 6] ];
// Rendimiento esperado
const output = ["A", "a", 1, "B", "b", 2, "C", "c", 3, "D", 4, 5, 6];
Así que escribo un código JavaScript para lograr resultados,
Array.prototype.insert = function ( index, item ) { this.splice( index, 0, item ); }; let lengthInputArray = input.length; let outputArray = []; let lengthArray = []; for(let indexInput = 0; indexInput < input.length; indexInput++){ lengthArray.push(input[indexInput].length); } let maxLen = Math.max(...lengthArray); for(let maxIndex = 0; maxIndex < maxLen; maxIndex++){ for (var indexArr of input) { if(indexArr.length <= maxLen){ var tobeInsertValue = indexArr[maxIndex]; if(tobeInsertValue != undefined){ outputArray.push(tobeInsertValue); } } } } console.log("outputArray : " + outputArray);
¿Alguien puede sugerirme una buena solución o una forma óptima de resolver el problema?
También puede intentar transponer la matriz en función del índice de matriz más largo y luego usar flat
y filter
para resaltar la forma plana sin ningún elemento indefinido (indefinido debido a la longitud desigual de los elementos de la matriz)
let input = [ ["A", "B", "C", "D"], ["a", "b", "c"], [1, 2, 3, 4, 5, 6] ]; let arrayLen = input.map(x => x.length); let maxLen = Math.max(...arrayLen) let maxIndex = arrayLen.indexOf(maxLen) console.log(input[maxIndex].map((_, colIndex) => input.map(row => row[colIndex])).flat().filter(x => x));
Solo un bucle anidado simple puede funcionar, siempre que maneje adecuadamente la longitud final:
const input = [ ["A", "B", "C", "D"], ["a", "b", "c"], [1, 2, 3, 4, 5, 6] ]; const maxLen = Math.max(...input.map(({ length }) => length)); let out = []; for (let i = 0; i < maxLen; i++) { for (let j = 0; j < input.length; j++) { if (input[j].length > i) { out.push(input[j][i]); } } } console.log(out);
.as-console-wrapper { max-height: 100% !important; top: auto; }
Recorrí cada uno de los subconjuntos en orden y agregué los valores en la posición correcta al conjunto de salida en el orden correcto.