Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

177
Vistas
JavaScript: better/cleaner functional way to find item from a nested array

I am trying to write a find function to find items from matched items from a potentially nested array (without having to flat the array first) and I am trying to write in a FP way.

Here is my attempt:

const nestedArray = [
  [{ id: 1 }],
  [{ id: 2 }],
  [{ id: 3 }, [{ id: 4 }]],
  { id: 5 },
]

function findTarget(arr, predicate) {
  const helper = ([x, ...xs]) =>
    x === undefined
      ? null
      : predicate(x)
      ? x
      : Array.isArray(x)
      ? helper(x) ?? helper(xs)
      : helper(xs)

  return helper(arr)
}

findTarget(nestedArray, (item) => item.id === 5)

I think it works but it is not super readable and I am sure there are better ways to write such a function.

about 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

Here's how I would implement this using recursion:

function findTarget(value, predicate) {
  const isArray = Array.isArray(value);

  // Base case: if value is not array and predicate matches, we found a match
  if (!isArray) {
    if (predicate(value)) return value;
    return null;
  }

  // value must be an array, so run recursion and see if value exists
  for (const item of value) {
    const foundItem = findTarget(item, predicate);
    if (foundItem !== null) {
      return foundItem;
    }
  }

  // nothing found
  return null;
}

does the same thing that your code does and imo looks cleaner.

about 4 years ago · Santiago Trujillo Denunciar

0

Since your example is calling predicate(x) in the first place, it will return a false positive when matching an array with an id: 5 property, so the Array.isArray(x) should go first to avoid this:

const nestedArray = [
  Object.assign([{ id: 1 }], { id: 5 }),
  [{ id: 2 }],
  [{ id: 3 }, [{ id: 4 }], null, [[{ id: 5 }]]],
  { id: 6 },
]

function findTargetLoop (arr, match) {
  if (!Array.isArray(arr))
    return arr && match(arr) ? arr : null;
  let item, i = 0;
  while (!(item = findTargetLoop(arr[i++], match)) && i < arr.length);
  return item ?? null;
}

const findTargetFunc = (arr, match, next) =>
  (next = ([item, ...rest]) =>
    Array.isArray(item) ? next(item) ?? next(rest)
    : item && match(item) ? item
    : rest.length ? next(rest) : null)(arr);


const match = item => item.id === 5;

console.log('with iterations', findTargetLoop(nestedArray, match));

console.log('pure functional', findTargetFunc(nestedArray, match));

about 4 years ago · Santiago Trujillo Denunciar

0

Here's one approach I can think of. It uses the init function as a sentinel value to distinguish whether the element being searched for has already been found. Before returning, it invokes the accumulated value which is either () => undefined, or () => curr capturing the first element that matches the predicate.

const flatFind = (array, predicate) => {
  const init = () => undefined
  const reducer = (prev, curr) => (
    prev === init
    ? Array.isArray(curr)
      ? curr.reduce(reducer, init)
      : predicate(curr)
        ? () => curr
        : init
    : prev
  )
  return array.reduce(reducer, init)()
}

const nestedArray = [
  [{ id: 1 }],
  [{ id: 2 }],
  [{ id: 3 }, [{ id: 4 }]],
  { id: 5 },
]

console.log(flatFind(nestedArray, item => item.id === 5))

about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda