Best way to flatten an object with array properties into one array JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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
]
raja
Published on 23-Nov-2020 10:56:00
Advertisements