- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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];
Example
Following is the code −
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));
Output
Following is the output in the console −
[ 1, 5, 44, 67, 3, 2, 5, 7, 4, 3, 7, 6 ]
Advertisements