Junior — Middle
How do the findIndex and indexOf methods differ when searching for elements in an array?
sobes.tech AI
Answer from AI
In Python, lists have the index() method, and strings and other sequences have the find() method. However, the question mentions findIndex and indexOf — these are JavaScript methods, not Python.
Regarding JavaScript:
indexOfsearches for an element in an array and returns the index of the first occurrence or -1 if not found.findIndextakes a predicate function and returns the index of the first element for which the function returns true, or -1 if none match.
Example in JavaScript:
const arr = [5, 12, 8, 130, 44];
console.log(arr.indexOf(12)); // 1
const isLargeNumber = (element) => element > 13;
console.log(arr.findIndex(isLargeNumber)); // 3
In Python, to find the index of an element, use the list.index(value) method, which returns the index of the first occurrence or raises an exception if not found. For conditional searches, you can use generators with next() and enumerate().