Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

findindex method javascript

// .findIndex only accepts a callback function. 
// returns the index of first value for which the function is true

const cities = [
  "Orlando",
  "Dubai",
  "Edinburgh",
  "Chennai",
  "Denver",
  "Eskisehir",
  "Medellin",
  "Yokohama",
  "Denver",
];

const findIndexOfCity = (element) => {
  return element === "Accra" || element === "Yokohama";
};

console.log(cities.findIndex(findIndexOfCity));
// Expected output is 7

//callback functions can take up to 3 arguments. 
//The 1st argument, regardless of what you name it, is always 
//assigned the element being checked. The 2nd argument, optional, 
//is the index of this element. The 3rd argument, also optional, 
//is the entire array.

const findIndexOfLastCity = (element, index) => {
  return element === "Denver" && index > 4;
};

console.log(cities.findIndex(findIndexOfLastCity));
//expected output is 8 (skipped "Denver" at index 4)
Source by developer.mozilla.org #
 
PREVIOUS NEXT
Tagged: #findindex #method #javascript
ADD COMMENT
Topic
Name
9+2 =