javascript – Sorting Nested Array

Overall your code is readable and it seems reasonably clear what it does. As you said, the code is somewhat inefficient if one of the arrays is much larger than the rest, but for your example (and honestly, even if you had a thousand items in one array), the time cost would probably be negligible, unless the number of arrays in arr is very very large.

Number.MIN_VALUE

Number.MIN_VALUE is not what you think it is. It represents the smallest positive number that can be represented, not the most negative number. As a result, if you use let arr = (); you end up with a biggestLength that is slightly more than 0 and run your second loop… only to figure out that you do not have items. Or arrats, This in itself does not break anything, but you could just initialise biggestLength to 0 and things would work out fine.

Optimising

As I said earlier, the amount of time it takes to do this operation is negligible, even if you have 100 items in the first array. With 11 items over 4 arrays (16 operations) it takes me 0.010ms, and with 107 items over 4 arrays (400 operations) it takes me 0.025ms.

const arr = (
  (1, 2, 4, 6),
  (3, 8, 7),
  (12, 13),
  (),
  (9, 10)
);

function getUnfoldedArray(arr) {
  let biggestLength = Number.MIN_VALUE;
  for (let i = 0; i < arr.length; i++) {
    if (arr(i).length > biggestLength) {
      biggestLength = arr(i).length;
    }
  }

  let result = ();
  for (let l = 0; l < biggestLength; l++) {
    for (let k = 0; k < arr.length; k++) {
      if (arr(k)(l) !== undefined) {
        result.push(arr(k)(l))
      }
    }
  }
  
  return result;
}

console.time('First run is always slower');
getUnfoldedArray(arr);
console.timeEnd('First run is always slower');

console.time('time1');
const result = getUnfoldedArray(arr);
console.timeEnd('time1'); // 0.010ms

arr(0) = ();
for (let i = 0; i < 100; i++) {
  arr(0).push(i);
}

console.time('time2');
const result2 = getUnfoldedArray(arr);
console.timeEnd('time2'); // 0.025ms

console.log(result);
console.log(result2);

If you don’t mind destroying the array you are doing stuff on, you can potentially use Array.shift(). You could also splice out any empty arrays then, but keep in mind that loops will mess up when you do that. Overall your code would probably get more complicated for not a lot of gain.