From 40c919330e8f6b09934e770af093dd9691438beb Mon Sep 17 00:00:00 2001 From: Isabelle Viktoria Maciohsek Date: Mon, 28 Dec 2020 12:07:53 +0200 Subject: [PATCH] Add linearSearch --- snippets/linearSearch.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 snippets/linearSearch.md diff --git a/snippets/linearSearch.md b/snippets/linearSearch.md new file mode 100644 index 000000000..91143c366 --- /dev/null +++ b/snippets/linearSearch.md @@ -0,0 +1,25 @@ +--- +title: linearSearch +tags: algorithm,array,beginner +--- + +Finds the first index of a given element in an array using the linear search algorithm. + +- Use a `for...in` loop to iterate over the indexes of the given array. +- Check if the element in the corresponding index is equal to `item`. +- If the element is found, return the index, using the unary `+` operator to convert it from a string to a number. +- If the element is not found after iterating over the whole array, return `-1`. + +```js +const linearSearch = (arr, item) => { + for (const i in arr) { + if (arr[i] === item) return +i; + } + return -1; +}; +``` + +```js +linearSearch([2, 9, 9], 9); // 1 +linearSearch([2, 9, 9], 7); // -1 +```