Refactor and Optimize Nested Loops for Product Price Analysis
Improve the readability, maintainability, and performance of a deeply nested JavaScript function that analyzes product prices across multiple categories and regions.
Challenge prompt
You are given a messy JavaScript function that takes an array of category objects. Each category contains multiple regions, and each region contains a list of product prices. The function computes the average price per region and returns an object with categories as keys and values as arrays of averages per region. Your task is to refactor this function to improve code clarity, reduce nesting, and optimize performance without changing its output or signature.
Guidance
- • Focus on breaking down the nested loops by using helper functions or array methods like map and reduce.
- • Consider ways to eliminate unnecessary temporary variables and combine operations.
- • Keep the function's output structure identical to ensure no behavioral changes.
Hints
- • Use Array.prototype.map to transform arrays more declaratively.
- • Use Array.prototype.reduce to calculate sums and averages efficiently.
- • Avoid deeply nested for-loops by flattening the data processing steps.
Starter code
function analyzePrices(categories) {
let result = {};
for (let i = 0; i < categories.length; i++) {
let category = categories[i];
let regionAverages = [];
for (let j = 0; j < category.regions.length; j++) {
let region = category.regions[j];
let total = 0;
for (let k = 0; k < region.products.length; k++) {
total += region.products[k];
}
let avg = region.products.length > 0 ? total / region.products.length : 0;
regionAverages.push(avg);
}
result[category.name] = regionAverages;
}
return result;
}Expected output
analyzePrices([{ name: 'Electronics', regions: [ { products: [100, 200, 300] }, { products: [400, 500] } ] }, { name: 'Books', regions: [ { products: [10, 20] }, { products: [] } ] }]) // Output: { Electronics: [200, 450], Books: [15, 0] }
Core concepts
Challenge a Friend
Send this duel to someone else and see if they can solve it.