function linearSearch(arr, key) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === key) {
return i;
}
}
return -1;
}
This implementation of the linear search algorithm uses a for loop to iterate through the input array, and compares each element with the key, until the key is found or the end of the array is reached.
It takes an array as the first argument and a key as the second argument, and returns the index of the key in the array if it's found and -1 if it's not found.
Here's an example of how the function can be used:
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log(linearSearch(arr, 3)); // 2
console.log(linearSearch(arr, 11)); // -1