Giả sử chúng ta có hai mảng như sau:
const meals = ["breakfast", "lunch", "dinner"]; const ingredients = [ ["eggs", "yogurt", "toast"], ["falafel", "mushrooms", "fries"], ["pasta", "cheese"] ];
Chúng ta cần viết một hàm JavaScript nhận hai mảng như vậy và ánh xạ các mảng con trong mảng thứ hai đến các chuỗi tương ứng của mảng đầu tiên.
Do đó, đầu ra cho các mảng trên sẽ trông như:
const output = {
"breakfast" : ["eggs", "yogurt", "toast"],
"lunch": ["falafel", "mushrooms", "fries"],
"dinner": ["pasta", "cheese"]
};
Ví dụ
Mã thực hiện:
const meals = ["breakfast", "lunch", "dinner"];
const ingredients = [
["eggs", "yogurt", "toast"],
["falafel", "mushrooms", "fries"],
["pasta", "cheese"]
];
const combineMealAndIngredient = (meals, ingredients) => {
const res = {};
meals.forEach(function (el, ind) {
this[el] = ingredients[ind];
}, res);
return res;
};
console.log(combineMealAndIngredient(meals, ingredients));
Kết quả
Kết quả trong console:
{
breakfast: [ 'eggs', 'yogurt', 'toast' ],
lunch: [ 'falafel', 'mushrooms', 'fries' ],
dinner: [ 'pasta', 'cheese' ]
}