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.
aandbare arrays of numbers and strings (one array can have both). Each one can have any length, also0.- Keep the order: first the elements of
ain their order, then the elements ofbin 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
aorbis empty. Do not returnaorbitself. - Do not change (do not mutate)
aorb.
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...
- Input
mergeArrays([ 1, 2, 3 ], [ 4, 5 ])Expected[ 1, 2, 3, 4, 5 ] - Input
mergeArrays([], [ 'x' ])Expected[ 'x' ]
Hidden tests run on Submit