
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Best Way to Flatten an Object with Array Properties into One Array in JavaScript
Suppose, we have an object of arrays like this −
const obj = { arr_a: [9, 3, 2], arr_b: [1, 5, 0], arr_c: [7, 18] };
We are required to write a JavaScript function that takes in one such object of arrays. The function should construct an flattened and merged array based on this object.
Therefore, the final output array should look like this −
const output = [9, 3, 2, 1, 5, 0, 7, 18];
Example
const obj = { arr_a: [9, 3, 2], arr_b: [1, 5, 0], arr_c: [7, 18] }; const objectToArray = (obj = {}) => { const res = []; for(key in obj){ const el = obj[key]; res.push(...el); }; return res; }; console.log(objectToArray(obj));
Output
And the output in the console will be −
[ 9, 3, 2, 1, 5, 0, 7, 18 ]
Advertisements