Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

175
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!