0

I am trying to return an object array from a function and assign it to a variable

function contactsbuilder(contacts){
    var contactsarray = [];
    parent.$(contacts).each(function(i,contact){
        contactsarray.push(somevalues);
        if(contacts.length == i+1){
            console.log("coming in here?");
            return contactsarray;
        }
    });
};

Now I tried to assign it like

var contactsarray =contactsbuilder(customdetails.contacts);

but contactsarray always stays undefined even after the console log is made. I tried setTimeout but no luck

I tried a simpler one without foreach

function sample(){
var xx= ["ss","ssdfds"];
return xx;
}
var something = sample()

Now something gets array value, what is wrong in my case?

Vignesh Subramanian
  • 7,161
  • 14
  • 87
  • 150

1 Answers1

2

You need to returning the array inside the each() callback which doesn't have any effect. And nothing is returning from the contactsbuilder function, so move the return statement outside.

function contactsbuilder(contacts){
    var contactsarray = [];
    parent.$(contacts).each(function(i,contact){
        contactsarray.push(somevalues);
        if(contacts.length == i+1){
            console.log("coming in here?");
        }
    });
    return contactsarray;// return the array
};
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188