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?

2
  • what should ` parent.$(contacts)` mean? Commented May 18, 2016 at 11:35
  • it is just an for each for an array of objects $(somearray).each Commented May 18, 2016 at 11:37

1 Answer 1

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
};
Sign up to request clarification or add additional context in comments.

6 Comments

thanks, wont it return empty array if it has like 1000 values in it? or when I want to make some ajax calls and return values?
@vignesh : I couldn't get you
for example, if I want to make some ajax call inside that $().each, wont it return the contactsarray before the ajax call returns some value?
@vignesh : ajax is asynchronous and it may complete any time .... the function will not wait for the ajax to execute
thanks ji, what should i do if i am going to use an ajax call inside that function and return value based on its result?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.