Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
8,048 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!');
  }