101 exercises JavaScript need help with #94

Write a function called highestPriceBook that takes in the above defined array of objects “books” and returns the object containing the title, price, and author of the book with the highest priced book.
Hint: Much like sometimes start functions with a variable set to zero, you may want to create a object with the price set to zero to compare to each object’s price in the array

const books = [
{
“title”: “Genetic Algorithms and Machine Learning for Programmers”,
“price”: 36.99,
“author”: “Frances Buontempo”
},
{
“title”: “The Visual Display of Quantitative Information”,
“price”: 38.00,
“author”: “Edward Tufte”
},
{
“title”: “Practical Object-Oriented Design”,
“author”: “Sandi Metz”,
“price”: 30.47
},
{
“title”: “Weapons of Math Destruction”,
“author”: “Cathy O’Neil”,
“price”: 17.44
}

This is what I have got so far;

function highestPriceBook(input){
var comp = {“title”:"",“author”:"",“price”:0};
for(var i = 0; i < input.length; i++){
if(comp.price < input[i].price){
comp = input[i];
}
}
return comp;
}

What I want to do is take in all the price numbers and compare them to the highest number in the array. Then take the object with the highest price and return it. I cant seem to figure it out, can someone shed some light on this problem? thank you

Hi @ShelbyHughes! If you share your project name I can go to the project and walk through it with you, or if you’d rather work it out here, could you tell me which part in particular you’re snagged on?

I can get the highest number or I can get the name but I cannot get it to return the entire object, the answer should look like:

assert(highestPriceBook(books), {
“title”: “The Visual Display of Quantitative Information”,
“price”: 38.00,
“author”: “Edward Tufte”
}, “Exercise 94”);

Ohhhh I see what you’re saying – I think the trick here is to compare the prices, but to save the entire object (when you assign it as the new highestPriceBook) or whatever. Does that make sense? Happy to look at code if that would be clearer!
So for example if I’m trying to find the highest mountain in a set of mountains, where a mountain looks like this:

{
  name: Aconcagua
  heightInMeters: 6961
  location: Argentina
}

My check might look like this:

   if (currentMountain.heightInMeters > highestMountain.heightInMeters){
      highestMountain = currentMountain;
   }

Hi,
I think this is what you need

function mostExpensive(bookArray) {
return bookArray.sort((a, b) => b.price - a.price);
}

mostExpensive(books)[0];

The [0] will return the most expensive book object.

A question like this is an opportunity to learn new ways of doing things :slight_smile:

My hint is to look at the reduce function … https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce