Skip to content

Instantly share code, notes, and snippets.

@AnkitMaheshwariIn
Last active March 24, 2022 11:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AnkitMaheshwariIn/2296c0f03d179a2faceab30b2eb2118e to your computer and use it in GitHub Desktop.
Save AnkitMaheshwariIn/2296c0f03d179a2faceab30b2eb2118e to your computer and use it in GitHub Desktop.
Code to search an item from an array using linear search
/* RUN THIS CODE AND OPEN YOUR CONSOLE TO SEE THE OUTPUT */
// Code to search an item from an array using linear search
// declare a function which will take two arguments: array and itemToSearch
const doLinearSearch = (arr, itemToSearch) => {
// iterate using for loop, where i is index and elem is each item
for (const [i, elem] of arr.entries()) {
if (elem === itemToSearch) {
// return index, if elem matched with item to search
return i
}
}
}
// declare an array
arr = [10, 20, 30, 40, 50, 60]
// declare item to search
const itemToSearch = 50
// call a function to search item from an array
// if item find this function will return index of an item
const itemIndex = doLinearSearch(arr, itemToSearch)
if (itemIndex > -1) {
console.log("Item found at index: " + itemIndex)
console.log("Item found is: " + arr[itemIndex])
} else {
console.log("Item not found")
}
/*
THE OUTPUT IS:
"Item found at index: 4"
"Item found is: 50"
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment