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()

Ivan Molina
Ivan Molina
2,870 Points

whats the purpose of the Spoiled Alert's answer?

...The instructor's Spoiled Alert code returns $4.49,..shoudn't return $6.99?

// Instructors Code
const products = [
  { name: 'hard drive', price: 59.99 },
  { name: 'lighbulbs', price: 2.59 },
  { name: 'paper towels', price: 6.99 },
  { name: 'flatscreen monitor', price: 159.99 },
  { name: 'cable ties', price: 19.99 },
  { name: 'ballpoint pens', price: 4.49 }
];

const product = products
  .filter(product => product.price < 10)
  .reduce((highest, product) => {
    if (highest.price > product.price) {
      return highest.price; //...---> return highest
    }
    return product.price;  // --->return product
  }, {price: 0});

  console.log(product);

.....my code to return just the Price that is the highest and less than 10:

const product = products
  .filter(product => product.price < 10)
  .reduce((highest, product) => {
    if (highest.price > product.price) {
      return highest.price; 
    }
    return product;  
  }, {price: 0});

1 Answer

Steven Parker
Steven Parker
220,425 Points

I believe you've discovered a bug in the code.

I wouldn't expect this to work, since the callback function passed to "reduce" returns a value, but the first parameter (and the dummy argument) are both product objects and not values. But if we make a few changes to account for this, it does work:

const product = products
  .filter(product => product.price < 10)
  .reduce((highestprice, product) => {
    if (highestprice > product.price) {
      return highestprice;
    }
    return product.price;
  }, 0);