JavaScript JavaScript Loops, Arrays and Objects Tracking Multiple Items with Arrays Useful Array Methods

how do we improve code to search for a singular or plural form of the items in stock?

Hi. I was wondering how we can improve the code to search for a singular or plural form of the items in stock. For example, a search for 'apple' shows no apple in stock but a search for 'apples' shows that we do have this product in stock. Thanks!

1 Answer

Austin Harms
Austin Harms
5,447 Points

There's probably a more robust way to write this, but it does the trick for this simple example. I use the findIndex method quite a bit, it's super useful. Basically it returns the first item of the array that satisfies the testing function. So in my example, I'm checking against the user's search input, as well as the input plus an "s" at the end. If it finds either, the code in the if block will run.

MDN findIndex

var inStock = ['apples', 'carrots', 'bananas'];
var search;

search = prompt('Search our fruit.');
search = search.toLowerCase();

if(inStock.findIndex(fruit => fruit === search || fruit === (search + 's')) > -1) {
        alert('in stock!');
  }