मान लीजिए, हमारे पास ऐसी दो सरणियाँ हैं −
const meals = ["breakfast", "lunch", "dinner"]; const ingredients = [ ["eggs", "yogurt", "toast"], ["falafel", "mushrooms", "fries"], ["pasta", "cheese"] ];
हमें एक JavaScript फ़ंक्शन लिखना आवश्यक है जो ऐसी दो सरणियाँ लेता है और दूसरी सरणी में उप-सरणियों को पहली सरणी के संबंधित स्ट्रिंग्स से मैप करता है।
इसलिए, उपरोक्त सरणियों के लिए आउटपुट इस तरह दिखना चाहिए −
const output = { "breakfast" : ["eggs", "yogurt", "toast"], "lunch": ["falafel", "mushrooms", "fries"], "dinner": ["pasta", "cheese"] };उदाहरण
इसके लिए कोड होगा −
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));आउटपुट
और कंसोल में आउटपुट होगा −
{ breakfast: [ 'eggs', 'yogurt', 'toast' ], lunch: [ 'falafel', 'mushrooms', 'fries' ], dinner: [ 'pasta', 'cheese' ] }