search array until value is found in javascript

To search an array until a value is found in JavaScript, you can use a for loop to iterate through the array and check each element using a conditional statement inside the loop. Once the value is found, you can exit the loop using a break statement.

Here's an example function that searches for a value in an array:

index.tsx
function searchArray(array, value) {
  for (let i = 0; i < array.length; i++) {
    if (array[i] === value) {
      return i; // return array index if value is found
    }
  }
  return -1; // return -1 if value is not found
}

// Example usage:
const arr = [1, 2, 3, 4, 5];
const valueToFind = 3;
const index = searchArray(arr, valueToFind);
console.log(index); // output: 2 (index of value 3 in the array)
407 chars
15 lines

In this example, the searchArray function takes an array and a value to search for as arguments. It then iterates through the array using a for loop, checking each element using the === operator to compare it to the value being searched for. If the value is found, the function returns the index of the element in the array. If the value is not found after iterating through the entire array, the function returns -1.

gistlibby LogSnag