Rajendra
Rajendra

Reputation: 223

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 ?

Upvotes: 0

Views: 69

Answers (2)

NightEye
NightEye

Reputation: 11214

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

Upvotes: 1

Jack Bashford
Jack Bashford

Reputation: 44135

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.

Upvotes: 0

Related Questions