Linear Search in JavaScript

Anna Vlasenko
1 min readMay 10, 2021

--

Linear Search checking every single element in an array or string one at a time and compare if it’s the value we want. Keep going until we find it or we get to the end.

JavaScript build-in methods indexOf, includes, find, findIndex are Linear Search. For example, we have an array of numbers, and looking for 55, Linear Search starts from the begging and checking every value if it is 55.

Linear search

Custom IndexOf

Let's implement the custom method IndexOf, basically, we just loop over the array and check if the current value is equal to searched value.

function customIndexOf(arr, value){
if(arr.length === 0) return -1
for(let i = 0; i < arr.length; i++){
if(arr[i] === value) {
return i
}
}
return -1
}
console.log(customIndexOf([2, 4, 55, 7], 55)) // 2

And implementation when we can use custom indexOf as an array method

Array.prototype.customIndexOf = function(value) {
if(this.length === 0) return -1
for(let i = 0; i < this.length; i++){
if(this[i] === value) {
return i
}
}
return -1
}
console.log([2, 4, 55, 7].customIndexOf(55)) // 2

Linear Search Big O

As input grows the number of iteration grows, so Big O Notation is linear, O(n) for Linear Search and for build-in JavaScript search methods.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Anna Vlasenko
Anna Vlasenko

Written by Anna Vlasenko

Frontend Developer | ❤️ React

No responses yet

Write a response