Add all records from one array to each record from a different array in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose we have two arrays of strings that contain data about some users like this −

const users = ['Rahul', 'Dinesh', 'Rohit'];
const data = ["SOP1", "SOP2","SOP3","SOP4"];

We are required to write a JavaScript function that takes in two such arrays and returns a new array of objects.

The new array should contain an object for each possible combination of the user and data array.

Therefore, for the above array, the output should look like −

const output = [
   { User: 'Rahul', SOP: 'SOP1' },
   { User: 'Rahul', SOP: 'SOP2' },
   { User: 'Rahul', SOP: 'SOP3' },
   { User: 'Rahul', SOP: 'SOP4' },
   { User: 'Dinesh', SOP: 'SOP1' },
   { User: 'Dinesh', SOP: 'SOP2' },
   { User: 'Dinesh', SOP: 'SOP3' },
   { User: 'Dinesh', SOP: 'SOP4' },
   { User: 'Rohit', SOP: 'SOP1' },
   { User: 'Rohit', SOP: 'SOP2' },
   { User: 'Rohit', SOP: 'SOP3' },
   { User: 'Rohit', SOP: 'SOP4' }
];

Example

The code for this will be −

const users = ['Rahul', 'Dinesh', 'Rohit'];
const data = ["SOP1", "SOP2","SOP3","SOP4"];
const multiplyUserData = (users = [], data = []) => {
   const res = [];
   users.forEach(user => {
      data.forEach(el => {
         res.push({
            'user': user,
            'sop': el
         });
      });
   });
   return res;
};
console.log(multiplyUserData(users, data));

Output

And the output in the console will be −

[
   { user: 'Rahul', sop: 'SOP1' },
   { user: 'Rahul', sop: 'SOP2' },
   { user: 'Rahul', sop: 'SOP3' },
   { user: 'Rahul', sop: 'SOP4' },
   { user: 'Dinesh', sop: 'SOP1' },
   { user: 'Dinesh', sop: 'SOP2' },
   { user: 'Dinesh', sop: 'SOP3' },
   { user: 'Dinesh', sop: 'SOP4' },
   { user: 'Rohit', sop: 'SOP1' },
   { user: 'Rohit', sop: 'SOP2' },
   { user: 'Rohit', sop: 'SOP3' },
   { user: 'Rohit', sop: 'SOP4' }
]
raja
Published on 21-Nov-2020 14:54:09
Advertisements