Code Lab

Merge two arrays

MediumArrays10 min

Write a function mergeArrays(a, b) that returns a new array with all elements of a and then all elements of b.

  • a and b are arrays of numbers and strings (one array can have both). Each one can have any length, also 0.
  • Keep the order: first the elements of a in their order, then the elements of b in their order.
  • Keep repeated values. If a value is in both arrays, or twice in one array, it is in the result every time.
  • Always return a new array, even when a or b is empty. Do not return a or b itself.
  • Do not change (do not mutate) a or b.

The interviewer asked for exactly one for loop. The tests check only the result; keep to the rule yourself. One loop over the indexes from 0 to a.length + b.length - 1 is enough.

Examples

mergeArrays([1, 2, 3], [4, 5])

Returns [ 1, 2, 3, 4, 5 ]

mergeArrays([], ['x'])

Returns [ 'x' ]

Asked at Mastercard · Source

Loading the editor...
  1. InputmergeArrays([ 1, 2, 3 ], [ 4, 5 ])
    Expected[ 1, 2, 3, 4, 5 ]
  2. InputmergeArrays([], [ 'x' ])
    Expected[ 'x' ]

Hidden tests run on Submit.