0

I have seen this question and from what I have worked on it contained the answer but unfortunately it used Python instead of Javascript. So I would like to ask an similar question.

I have an Javascript array which follows this format:

[[1,2,3],[4,5,6,7,8],[9,10]]

The function I am looking for should turn this array and pad all of them with zeros until they have all reached the max length (for this example as shown above it is 5). The function should output an array with this format:

[[1,2,3,0,0], [4,5,6,7,8],[9,10,0,0,0]]

2 Answers2

1

You can first find the longest subarray, and then create new subarrays of that length and fill them up with the original data:

function padArray(arr) {
  let length = Math.max(...arr.map(row => row.length));
  return arr.map(row => Array.from({length}, (_, i) => i < row.length ? row[i] : 0)); 
}

let arr = [[1,2,3],[4,5,6,7,8],[9,10]];
console.log(padArray(arr));
trincot
  • 317,000
  • 35
  • 244
  • 286
0

Calculate the remaining items and concat at the end.

const data = [[1,2,3],[4,5,6,7,8],[9,10]];

const result = data.reduce((r, c) => {
    const remainingLen = 5 - c.length;
    if (remainingLen > 0) {
        c = [].concat(c, new Array(remainingLen).fill(0));
    }
    
    r.push(c);
    return r;
}, []);

console.log(result);
Kunal Mukherjee
  • 5,775
  • 3
  • 25
  • 53