Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Array Iteration Methods Combining Array Methods Combining filter() and reduce()

There is something really bizarre going on with this challenge. Fails in the challenge workspace, but on offline.

What is going on here? This exact code fails in the challenge workspace but is successful in my own offline workspace. I used a copy and paste to prove it.

const purchaseItems = [
    {
        name: 'apples',
        dept: 'groceries',
        price: 2.49
    },
    {
        name: 'bread',
        dept: 'groceries',
        price: 2.99
    },
    {
        name: 'batteries',
        dept: 'electronics',
        price: 5.80
    },
    {
        name: 'eggs',
        dept: 'groceries',
        price: 3.99
    },
    {
        name: 't-shirts',
        dept: 'apparel',
        price: 9.99
    }
];
let groceryTotal;

// groceryTotal should be: 9.47
// Write your code below
groceryTotal = purchaseItems
  .filter(item => item.dept === 'groceries')
  .reduce((total, item) => total + item.price, 0)
  .toFixed(2);
app.js
const purchaseItems = [
    {
        name: 'apples',
        dept: 'groceries',
        price: 2.49
    },
    {
        name: 'bread',
        dept: 'groceries',
        price: 2.99
    },
    {
        name: 'batteries',
        dept: 'electronics',
        price: 5.80
    },
    {
        name: 'eggs',
        dept: 'groceries',
        price: 3.99
    },
    {
        name: 't-shirts',
        dept: 'apparel',
        price: 9.99
    }
];
let groceryTotal;

// groceryTotal should be: 9.47
// Write your code below
groceryTotal = purchaseItems
  .filter(item => item.dept === 'groceries')
  .reduce((total, item) => total + item.price, 0)
  .toFixed(2);

console.log(groceryTotal);

2 Answers

Steven Parker
Steven Parker
220,683 Points

:warning: Be careful about testing a challenge in an external REPL. If is very easy to misinterpret the results.

The challenge is expecting the result to be a number, but by performing "toFixed" it is being converted to a string.

For best results, always do only what a challenge asks.

Seriously? I'll try it.

I'll be damned. You were right.