# JavaScript - Linear search algorithm

## JavaScript Searching Algorithm: Exercise-2 with Solution

Write a JavaScript program to find the first index of a given element in an array using the linear search algorithm.

From Wikipedia -

In computer science, a linear search or sequential search is a method for finding an element within a list. It sequentially checks each element of the list until a match is found or the whole list has been searched.

A linear search runs in at worst linear time and makes at most n comparisons, where n is the length of the list. If each element is equally likely to be searched, then linear search has an average case of (n+1)/2 comparisons, but the average case can be affected if the search probabilities for each element vary. Linear search is rarely practical because other search algorithms and schemes, such as the binary search algorithm and hash tables, allow significantly faster searching for all but short lists.

**Test Data:**

([1, 2, 3, 4, 5, 6, 7, 8, 9], 3) -> 2

([1, 2, 3, 4, 5, 6, 7, 8, 9], 9) -> 8

([1, 2, 3, 4, 5, 6, 7, 8, 9], 1) -> 0

([1, 2, 3, 4, 5, 6, 7, 8, 9], 0) -> -1

**Sample Solution: **

**JavaScript Code:**

```
const linearSearch = (arr, item) => {
for (const i in arr)
{
if (arr[i] === item)
return +i;
}
return -1;
};
const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9]
console.log(linearSearch(nums, 3))
console.log(linearSearch(nums, 9))
console.log(linearSearch(nums, 1))
console.log(linearSearch(nums, 0))
```

Sample Output:

2 8 0 -1

**Flowchart: **

**Live Demo: **

See the Pen javascript-searching-algorithm-exercise-2 by w3resource (@w3resource) on CodePen.

* To run the code mouse over on Result panel and click on 'RERUN' button.*

**Improve this sample solution and post your code through Disqus**

**Previous:** Index position of a word within a string.

**Next:** Ternary search algorithm.

**What is the difficulty level of this exercise?**

Test your Programming skills with w3resource's quiz.

## JavaScript: Tips of the Day

**Randomizes the order of the values of an array, returning a new array**

Example:

const tips_shuffle = ([...arr]) => { let x = arr.length; while (x) { const i = Math.floor(Math.random() * x--); [arr[x], arr[i]] = [arr[i], arr[x]]; } return arr; }; const foo = [2, 4, 6]; console.log(tips_shuffle(foo));

Output:

[4, 2, 6]

**Weekly Trends**- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook