Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Concatenating variable number of arrays into one - JavaScript
We are required to write a JavaScript function that takes in any number of JavaScript arrays and returns one single array with all the values from input arrays concatenated into it.
For example ? If the input arrays are ?
[1, 5], [44, 67, 3], [2, 5], [7], [4], [3, 7], [6]
Then the output should be ?
const output = [1, 5, 44, 67, 3, 2, 5, 7, 4, 3, 7, 6];
Using reduce() and concat()
The most straightforward approach uses the reduce() method combined with concat() to merge all arrays:
const a = [1, 5], b = [44, 67, 3], c = [2, 5], d = [7], e = [4], f = [3, 7], g = [6];
const concatArrays = (...arr) => {
const res = arr.reduce((acc, val) => {
return acc.concat(val);
}, []);
return res;
};
console.log(concatArrays(a, b, c, d, e, f, g));
[ 1, 5, 44, 67, 3, 2, 5, 7, 4, 3, 7, 6 ]
Using flat() Method
ES2019 introduced the flat() method which provides a cleaner solution:
const concatWithFlat = (...arrays) => {
return arrays.flat();
};
const a = [1, 5], b = [44, 67, 3], c = [2, 5];
console.log(concatWithFlat(a, b, c));
[ 1, 5, 44, 67, 3, 2, 5 ]
Using Spread Operator
The spread operator with concat() provides another elegant approach:
const concatWithSpread = (...arrays) => {
return [].concat(...arrays);
};
const x = [10, 20], y = [30, 40], z = [50];
console.log(concatWithSpread(x, y, z));
[ 10, 20, 30, 40, 50 ]
Comparison
| Method | Browser Support | Performance | Readability |
|---|---|---|---|
reduce() + concat() |
ES5+ | Good | Medium |
flat() |
ES2019+ | Best | High |
Spread + concat() |
ES6+ | Good | High |
Conclusion
For modern environments, use flat() for its simplicity and performance. For broader compatibility, the spread operator with concat() offers excellent readability while maintaining good browser support.
Advertisements
