Cho hai mảng:
const users = ['Rahul', 'Dinesh', 'Rohit']; const data = ["SOP1", "SOP2", "SOP3", "SOP4"];
Viết hàm trả về mảng đối tượng chứa mọi tổ hợp user-SOP (tích Descartes).
Kết quả: 12 đối tượng {User, SOP}.
Ví dụ
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));Kết quả
Kết quả in ra console:
[
{ 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' }
]