Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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'));

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading