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

239
Views
Receiving error when using Array.reduce on array

I'm trying to call this deepFilter function on an array with this structure but I am getting this error in the console: TypeError: Cannot read properties of undefined (reading 'reduce') and I can't figure out why. I'm sure it's something simple but I'm drawing a blank.

Can someone point me in the right direction?

const items = [
   {
      "name":"Name1",
      "id":58,
      "sites":[
         {
            "id":106,
            "name": "Name11",
            "items":[
               {
                  "name":"01",
               },
               {              
                  "name":"02",
               },
            ]
         }
      ]
   },
   {
      "name":"Name2",
      "id":47,
      "sites":[
         {
            "name":"Name22",
            "id":106,
            "items":[
               {
                  "name":"03",
               },
               {
                  "name":"04",
               },               
            ]   
         }
      ]
   }
];

const deepFilter = (items, value) => items.reduce((arr, cur) => {
  if (cur.name.includes(value)) arr.push(cur);
  else if (cur.hasOwnProperty('sites')) {
    const subItems = deepFilter(cur.subitems, value);
    if (subItems.length) {
      cur.subitems = subItems;
      arr.push(cur);
    }
  }
  else if (cur.hasOwnProperty('items')) {
    const subSubItems = deepFilter(cur.subsubitems, value);
    if (subSubItems.length) {
      cur.subsubitems = subSubItems;
      arr.push(cur);
    }
  }
  return arr;
}, []);

console.log(deepFilter(items, '02'));
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Because your value in cur.subitems is not an array.

you can fix it easily by adding && cur.subitems like this:

else if (cur.hasOwnProperty('sites') && cur.subitems) {

you are using recursion in your function so you should check values accordingly.

about 4 years ago · Juan Pablo Isaza 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!