Function that merges arrays into one in JavaScript
Let's now implement the merge function,
which takes an arbitrary number of arrays as
parameters and merges their elements
into one array.
Here is an example of how our function works:
let result = merge([1, 2, 3], [4, 5, 6], [7, 8, 9]);
console.log(result); // shows [1, 2, 3, 4, 5, 6, 7, 8, 9]
Let's get down to implementation. Let's first get the passed arrays as a single two-dimensional one:
merge([1, 2, 3], [4, 5, 6], [7, 8, 9]);
function merge(...arrs){
console.log(arrs); // shows [ [1, 2, 3,] [4, 5, 6], [7, 8, 9] ]
}
Let's now merge this two-dimensional array
into a one-dimensional one. We use the
concat method and the spread
operator for this:
let arrs = [ [1, 2, 3,], [4, 5, 6], [7, 8, 9] ];
let result = [].concat(...arrs);
console.log(result); // shows [1, 2, 3, 4, 5, 6, 7, 8, 9]
Let's add this code to our merge function:
function merge(...arrs) {
return [].concat(...arrs);
}
let result = merge([1, 2, 3], [4, 5, 6], [7, 8, 9]);
console.log(result); // shows [1, 2, 3, 4, 5, 6, 7, 8, 9]
As you can see, this function also turned out to be very concise.