Xavi3r
Xavi3r

Reputation: 42

Find the largest item in an array of objects and return name

I want to create a function to find the largest item in an array of objects based on the price property of the objects. The function should accept the array of items as a parameter and return the name of the most expensive item.

My thought process here is to use .map() in order to loop over the array and target the price property. Then use .reduce() and Math.max() to find the largest number. This, i believe, i have done successfully thus far. Now i need to write the code to return the itemName that is associated with the previously returned largest price.

All of the above should be contained within the same function. Example of my code thus far below.

      let items = [
  {
    itemName: "Good Habits",
    type: "book",
    price: 13.99
  },
  {
    itemName: "Macbook Pro",
    type: "computer",
    price: 299.99
  },
  {
    itemName: "Center of Gravity",
    type: "book",
    price: 15.00
  }
]

function mostExpensiveItem(items){
  let most = items.map(o => o.price).reduce(function(a, b) {
    return Math.max(a, b);
    })
    console.log(most)``
}

Upvotes: 0

Views: 1157

Answers (3)

ABGR
ABGR

Reputation: 5235

You could do this:

let items = [
  {
    itemName: "Good Habits",
    type: "book",
    price: 13.99
  },
  {
    itemName: "Macbook Pro",
    type: "computer",
    price: 299.99
  },
  {
    itemName: "Center of Gravity",
    type: "book",
    price: 15.00
  }
]

var res = items.reduce((acc, elem)=>{
  if(!acc.price || acc && acc.price < elem.price){
    acc = elem
  }
  return acc;
},{});
console.log(res.itemName)

Or, you can just sort descending on the basis of price and get the first element.

let items = [
  {
    itemName: "Good Habits",
    type: "book",
    price: 13.99
  },
  {
    itemName: "Macbook Pro",
    type: "computer",
    price: 299.99
  },
  {
    itemName: "Center of Gravity",
    type: "book",
    price: 15.00
  }
]

console.log(items.sort((a,b)=>  b.price - a.price)[0].itemName);
   

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386868

You could get an array of object with the same max proce and the map the name of the objects.

let items = [{ itemName: "Good Habits", type: "book", price: 13.99 }, { itemName: "Macbook Pro", type: "computer", price: 299.99 }, { itemName: "Center of Gravity", type: "book", price: 15.00 }],
    result = items
        .reduce((r, o, i) => {
            if (!i || r[0].price < o.price) return [o];
            else if (r[0].price === o.price) r.push(o);
            return r;
        }, [])
        .map(({ itemName }) => itemName);

console.log(result);

Upvotes: 0

Pedro Lima
Pedro Lima

Reputation: 1606

function mostExpensiveItem(items) {
    return items.reduce((p, v) => p.price > v.price ? p : v).itemName;
}

Upvotes: 1

Related Questions