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 blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More