skip to Main Content

i am tryong to make an array and be able to find the objects inside the array but whenever i do that it always gives me only the firstindex

let merchandise = [
{
  item:"Fan",
  price:800,
},
{
  item:"Television",
   price:500,
},
{
  item:"Headphone",
  price:700,
},
{
  item: "Refrigerator",
  price: 1000,
}
];
         
merchandise.find(items => items = prompt('what do you want to buy')) 
console.log(merchandise[0]);

2

Answers


  1. let merchandise = [
    {
      item:"Fan",
      price:800,
    },
    {
      item:"Television",
       price:500,
    },
    {
      item:"Headphone",
      price:700,
    },
    {
      item: "Refrigerator",
      price: 1000,
    }
    ];
    
    const whatToBuy = prompt('what do you want to buy')
    const index = merchandise.findIndex(item => item.item === whatToBuy) 
    console.log(index);
    Login or Signup to reply.
  2. In your example, this merchandise.find(items => items = prompt('what do you want to buy')) doesn’t make sense, because = is not comparing. And then you just output first element of array to console.
    It should be like this 👇:

    let merchandise = [
    {
      item:"Fan",
      price:800,
    },
    {
      item:"Television",
       price:500,
    },
    {
      item:"Headphone",
      price:700,
    },
    {
      item: "Refrigerator",
      price: 1000,
    }
    ];
    
    const answer = prompt('What do you want to buy?');
    const result = merchandise.find(o => o.item === answer) ?? 'Product not found';
    console.log(result);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search