Best way to flatten an object with array properties into one array 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
]

Updated on: 23-Nov-2020

616 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements