How to get single array from multiple arrays in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose, we have an array of arrays like this −

const arr = [
   [ {"c": 1},{"d": 2} ],
   [ {"c": 2},{"d": 3} ]
];

We are required to write a JavaScript function that takes in one such array as the first and the only argument.

The function should then convert the array (creating a new array) into array of objects removing nested arrays.

Therefore, the final output should look like this −

const output = [{"c": 1},{"d": 2},{"c": 2},{"d": 3}];

Example

const arr = [
   [ {"c": 1},{"d": 2} ],
   [ {"c": 2},{"d": 3} ]
];
const simplifyArray = (arr = []) => {
   const res = [];
   arr.forEach(element => {
      element.forEach(el => {
         res.push(el);
      });
   });
   return res;
};
console.log(simplifyArray(arr));

Output

And the output in the console will be −

[ { c: 1 }, { d: 2 }, { c: 2 }, { d: 3 } ]
raja
Published on 23-Nov-2020 07:15:40
Advertisements