

I publish a few articles and tutorials each week, please consider entering your email here if you’d like to be added to my once-weekly email list. Therefor, if the remainder does not equal zero, we have an odd number: function isOdd(i) arr.findIndex(isOdd) // 4Īs expected, the index (4) of the odd number (9) is returned! Want more advanced JavaScript?Ĭheck out: A Beginners Guide to Advanced JavaScript An even number will always have a remainder of 0. To do this, we’ll check the remainder of the number divided by 2. Next, we need a function to determine if a number is odd. What if we have an Array with all even numbers and one odd number? We can find the odd number with Array.find(). Note If the search value is a string, it is converted to a regular expression. The search () method returns -1 if no match is found. If it does, the value of that entry is returned. The search () method returns the index (position) of the first match. In the above example we are testing each entry in the array to see if it equals ‘b’. We’ll use an array with three entries: let arr = arr.find(k => k='b') // 'b' find() does not mutate or change the original Array.

If nothing passes, undefined is returned.find() method executes a callback function once for each element in the array until it finds a value that returns true.The find () method returns the first array element that meets the condition. Check if each value matches the condition. The Array.find() method returns the value of the first element in an array that passes a given test. Find the First Array Element matching a Condition in JavaScript To find the first array element that matches a condition: Use the Array.find () method to iterate over the array.
