AniUI Academy

Zip any number of arrays together

mediumArrays & Objects+250 XPPractice

Charting libraries hand you parallel arrays: one of labels, one of values, one of colours. To render a legend you need them as rows, one per data point.

Implement zip(...arrays) taking any number of arrays as separate arguments. Return an array of rows, where row i contains the element at index i from each input array, in the order the arrays were passed. The result has as many rows as the longest input array. Where a shorter array has no element at that index, use null. Calling zip() with no arguments returns an empty array, and so does zipping only empty arrays.

Arguments

...arraysArray[]
Any number of arrays to interleave, passed as separate arguments.

Returns

Array<Array> — An array of rows. Each row holds the matching index from every input, with null for shorter arrays.

Examples

zip([1, 2], ["a", "b"]);
// [[1, "a"], [2, "b"]]
zip([1, 2, 3], ["a"]);
// [[1, "a"], [2, null], [3, null]] — short arrays pad with null

zip([1], [2], [3]);  // [[1, 2, 3]] — any number of arrays
zip();               // []

What it has to do

  • Accept a variable number of array arguments.
  • Produce one row per index of the longest input array.
  • Fill gaps from shorter arrays with null.
  • Keep values in the same order the arrays were passed.
  • Return [] when called with no arguments or with only empty arrays.

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +250 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.