DEV Community

Marco Damaceno
Marco Damaceno

Posted on

2

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.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay