Array Search Methods in JavaScript
JavaScript provides built-in methods to find elements in an array. These tools help you locate positions or check if a value exists.
Here are the main methods you need to know:
indexOf() Finds the first index of a specific element. It returns -1 if the element is missing. Example: const fruits = ["Apple", "Banana", "Mango", "Banana"]; fruits.indexOf("Banana"); // Returns 1
lastIndexOf() Finds the last index of a specific element. It returns -1 if the element is missing. Example: const fruits = ["Apple", "Banana", "Mango", "Banana"]; fruits.lastIndexOf("Banana"); // Returns 3
includes() Checks if an element exists in your array. It returns true or false. Example: const fruits = ["Apple", "Banana", "Mango"]; fruits.includes("Mango"); // Returns true fruits.includes("Orange"); // Returns false
find() Returns the first element that meets your condition. It returns undefined if no match exists. Example: const numbers = [5, 12, 8, 20]; const result = numbers.find(num => num > 10); // Returns 12
findIndex() Returns the index of the first element that meets your condition. It returns -1 if no match exists. Example: const numbers = [5, 12, 8, 20]; const index = numbers.findIndex(num => num > 10); // Returns 1
findLast() Returns the last element that meets your condition. It searches from the end of the array. Example: const numbers = [5, 12, 8, 20]; const result = numbers.findLast(num => num > 10); // Returns 20
findLastIndex() Returns the index of the last element that meets your condition. Example: const numbers = [5, 12, 8, 20]; const index = numbers.findLastIndex(num => num > 10); // Returns 3
Summary:
• indexOf() gets the first index. • lastIndexOf() gets the last index. • includes() checks for existence. • find() gets the first matching value. • findIndex() gets the first matching index. • findLast() gets the last matching value. • findLastIndex() gets the last matching index.
Source: https://www.w3schools.com/js/js_array_search.asp
Full post: https://dev.to/kamalesh_ar_6252544786997/array-search-methods-in-javascript-23mk
