-2

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 Answers2

-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);
Konrad
  • 21,590
  • 4
  • 28
  • 64
-1

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);
imhvost
  • 4,750
  • 2
  • 8
  • 10