Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

116
Views
Need best case scenario

My input is const :

input = [
  ["A", "B", "C", "D"],
  ["a", "b", "c"],
  [1, 2, 3, 4, 5, 6]
 ];

// Expected output

const output = ["A", "a", 1, "B", "b", 2, "C", "c", 3, "D", 4, 5, 6];

So I write a JavaScript code to achieve output,

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

Can anybody suggest me about good solution or optimum way to solve the problem ?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You could also try transposing the array based on the longest array index then use flat and filter to bring out the flatten form without any undefined elements (undefined due to the unequal length of array elements)

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

about 4 years ago · Juan Pablo Isaza Report

0

Just a simple nested loop can work, as long as you appropriately handle the ending length:

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

I looped through each of the sub-arrays in order, and add the values at the correct position to the output array in their correct order.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!