0

I implemented a linear search algorithm using array.forEach(), but I can't figure out why it is not returning the index of the value I am searching for:

function linearSearch(array, value) {
  array.forEach((currentValue, index) => {
    if (value === currentValue) {
      return index;
    }
  });
    return -1; //if not found, return -1
}

const arr = [1,2,3,4,5];
const found = linearSearch(arr, 3);
console.log(found); //should be 2?
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title>Linear Search</title>
</head>
<body>
  <script src="main.js"></script>
</body>
</html>
InspectorDanno
  • 935
  • 2
  • 12
  • 23
  • 1
    Think about what function `return index;` is in and returning from. – Carcigenicate Jun 10 '19 at 22:08
  • Because the linearSearch doesn’t return a value? Nice algorithm though, tired of using indexOf? ;) – Mike Doe Jun 10 '19 at 22:09
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/forEach#Return_value => return value is not defined. Why not use `indexOf` - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf – Jaya Jun 10 '19 at 22:14

0 Answers0