Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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!');