DEV Community

Marco Damaceno
Marco Damaceno

Posted on

Another way to search for an element in an array in JavaScript

Is this useful for you?

function funnelSearch(arr, target, x = 0) {
  if (!arr.length) return;

  if (arr.length === 1 && arr[0] === target) {
    return target;
  }

  const left = arr[x];
  const right = arr[arr.length - x - 1];

  if (left === target || right === target) {
    return target;
  }

  if (x > (arr.length / 2)) return;

  return funnelSearch(arr, target, x + 1);
}

const numbers = [1,2,3,4,5,6,7,8,10];

console.log(funnelSearch(numbers, 1)); // 1
console.log(funnelSearch(numbers, 5)); // 5
console.log(funnelSearch(numbers, 0)); // undefined
console.log(funnelSearch('Marco Damaceno', 'D')); // D
Enter fullscreen mode Exit fullscreen mode

Honestly, I don't know the name of this technique.

It starts from index 0 AND from the last one incrementing the first index and decrementing the last index. And so on until it finds the element. If it does not find, returns undefined. It takes half time to go through all the elements than a usual that starts from index 0 to the last one.

I named it funnelSearch, because I didn't find anything like it documented on the web. Maybe, I didn't use the right words on my searches. BinarySearch?

If this technique has a known name, please, let me know.

PS: It also works for strings.

Top comments (0)