3

The Array.filter() method is having an asynchronous behavior. According to the documentation, it seems to me it's not supposed to work that way.

Moreover,it does not allow the reference to a callback, as usual in such cases.

I am limited in relation to the use of libraries, but also confuses me, how it reacts that way.

I am not also expert in ECMAScript, am i making some mistake?

I just want to filter one array and send the results to a HTML select element as several options.

I have something like this:

var selCompanyDeps = departments.filter(fromSelectedCompany);

fillSelect($("#selDeparts"), selCompanyDeps, 'departmentID', 'name', selectedID);

function fromSelectedCompany(value){
    var selectedCompany = $( "#SelComps" ).val();
    return (value.companyID===Number(selectedCompany));
}

Thanks

5
  • 5
    .filter is not an async method. Commented Aug 3, 2015 at 18:08
  • 1
    It does not provide a callback because it is not asynchronous. I cannot discern a question here. Commented Aug 3, 2015 at 18:09
  • What does departments contain? Commented Aug 3, 2015 at 18:19
  • Yes, i saw .filter wasn´t an async method tymeJV, and that's my question Petrichor. Commented Aug 4, 2015 at 7:22
  • aduch, departments is a array Commented Aug 4, 2015 at 7:22

1 Answer 1

7

Array.filter is not an asynchronous method, but what you appear to be confusing is the order of execution of a JavaScript programme.

When the browser parses your code, the browser will look for named functions and add them to the list of declared names in the current scope (known as function hoisting).

Therefore, fromSelectedCompany is executed before you call fillSelect, so your code is equivalent to the following:

function fromSelectedCompany(value){
    var selectedCompany = $( "#SelComps" ).val();
    return (value.companyID===Number(selectedCompany));
}

var selCompanyDeps = departments.filter(fromSelectedCompany);

fillSelect($("#selDeparts"), selCompanyDeps, 'departmentID', 'name', selectedID);
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks toothbrush, i knew about hoisting, i didn't knew there was also function hoisting.
Great!! It's working. I just put the function as anonymous function inside the .filter, and it solves the question. One more time, thanks @toothbrush, and thanks everyone who was trying to help var selCompanyDeps = departments.filter(function (value){ var selectedCompany = $( "#SelComps" ).val(); return (value.companyID===Number(selectedCompany)); });
@PedroGuedes OK, glad to have been of help.

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.