Home > Blockchain >  Return object from a recursive function that rearranges array of literal objects
Return object from a recursive function that rearranges array of literal objects

Time:10-22

I have a function that takes a literal object as an input. as an outcome it should return 2 arrays of objects.

It is a recursive function so the return happens at n-th recursion cycle with the following data:

//code
const filterObject = (object, array1 = null, array2 = null) => {
let a1 = array1 === null?[]: array1; //array1 is passed as a part of recursion and when recursed is not null
let a2 = array2 === null?[]: array2; //same here
...
//some filtering and object manipulation to create **composedObject**
...
if (condition x is met){
a1.push(composedObject)
}
if( condition y is met ){
a2.push(composedObject)
...
//filtering out parts of initial object that were used
//what is left is assembled into **untreatedObject**
...
if (there are still parts of the initial object that are left untreated){
 filterObject(untreatedObject, a1, a2); //here recursion happens and we pass these arrays there as well as they will continue to be populated
}
else if (everything is filtered and objects are ready){
console.log(a1) //values are present and correct
console.log(a2) //values are present and correct
 return { a: a1, b: a2};
}

/*
  where

   array1:[
   {
    a: 1,
    b: 'skdfhkdj',
    c:[
     {
       index:0,
       code :'red'
     },
     {
       index:1,
       code :'redcwrg'
     }
    ]
   }
  ],
  
 array2:[
   {
    a: 1,
    b: 'skdfhkdj',
    c:[
     {
       index:2,
       code :'redaxac'
     },
     {
       index:3,
       code :'reddd'
     }
    ]
   }
  ]
*/

const result = filterObject(object, null,null);
console.log(result); //**gives undefined**.   

QUESTION When i try to call this function const result = filterObject(object, null,null) (null,null here is the starting values for the arrays. they are assigned to [] in the beginning of the function and then when recursion happens they are sent too so that new arrays can be upserted)

and when i log it, the result is of type "undefined" and i am positive that the function does have the objects in array before return happens

So where can I be wrong?

Thanks in advance

CodePudding user response:

One import thing is missing: your code does not return the object returned from a recursive call. It only has a return for the base case. Your code doesn't perform the return of the other, recursive case.

So to put it clear, you need

return filterObject(untreatedObject, a1, a2);
  • Related