findIndex
Function
Objectives
-
Describe and use the findIndex function
-
Implement the findIndex on your own
function findIndex(array, callback) {
// findIndex code to be implemented
}
findIndex Definition
function callback(curElement, curIndex, array) {
// callback implemented by caller of function
}
Returns the index of the first element in the array for which the callback returns a truthy value. -1 is returned if the callback never returns a truthy value.
var arr = [3,4,6,2,1];
findIndex(arr, function(num, index, array) {
return num === 6;
});
findIndex Example: Find A Number
Returned Result:
2
var arr = [5,11,13,8,6,7];
findIndex(arr, function(num, index, array) {
return num % 2 === 0;
});
findIndex Example: Find First Even
Returned Result:
3
var langs = ["Java", "C++", "Python", "Ruby"];
findIndex(langs, function(lang, index, arr) {
return lang === "JavaScript";
});
findIndex Example: Could Not Find
Returned Result:
-1
var langs = ["Java", "C++", "JavaScript"];
findIndex(langs, function(lang, index, arr) {
lang === "JavaScript";
});
findIndex Example: Bad Callback
Returned Result:
-1
YOUR
TURN
findIndex Exercise
By Elie Schoppik
findIndex Exercise
- 2,866