javascriptintermediate10 minutes

Fix the Bug in Filtering and Summing Product Prices

The provided JavaScript function is intended to filter products by category and then calculate the total price of those filtered products. However, it contains bugs that prevent it from working correctly. Your task is to debug and fix the function so that it returns the correct total price for the specified category.

Challenge prompt

You are given a function `getTotalCategoryPrice(products, category)` that should filter the products array to only include items of the given category and then return the sum of their prices. However, the current implementation has logical errors that cause it to return incorrect results or NaN. Debug and fix the function to produce the correct total price.

Guidance

  • Check how the products array is filtered and ensure the filter condition is correct.
  • Review how the total price is accumulated; ensure the reduce function is implemented properly.
  • Confirm that the function returns a number and handles empty categories correctly.

Hints

  • Remember that Array.prototype.filter expects a function that returns true or false for each element.
  • Array.prototype.reduce needs an initial value to avoid issues when the filtered array is empty.

Starter code

function getTotalCategoryPrice(products, category) {
  const filtered = products.filter(product => {
    product.category = category;
  });

  const total = filtered.reduce((sum, product) => {
    sum += product.price;
  });

  return total;
}  

// Example products array:
const products = [
  { id: 1, name: 'Keyboard', category: 'electronics', price: 29 },
  { id: 2, name: 'Shirt', category: 'clothing', price: 15 },
  { id: 3, name: 'Mouse', category: 'electronics', price: 19 },
  { id: 4, name: 'Pants', category: 'clothing', price: 25 }
];

console.log(getTotalCategoryPrice(products, 'electronics'));

Expected output

48

Core concepts

Array.prototype.filterArray.prototype.reduceArrow functionsDebugging logical errors

Challenge a Friend

Send this duel to someone else and see if they can solve it.