0

I have script to show dropdown in select box. The script currently i am using is

jQuery.each( dslr, function( index, dslrgp) {
    var aslrp= dslrgp.aslrp;
    jQuery.each( aslrp, function(index2, pslrp) {
        var found = 0;
        jQuery.each( dropdown, function(index3, dditem) {
            if (dditem.countryname == pslrp.countryname)
            {
                foundit = 1;
            }
        });
        if (foundit == 0)
            dropdown.push(pslrp);

    });
});

How can i convert this to pure javascript. Because if i am using this

dslr.forEach(function( index, dslrgp) {
    var aslrp= dslrgp.aslrp;
    aslrp.forEach(function(index2, pslrp) {
        var found = 0;
        dropdown.forEach(function(index3, dditem) {
            if (dditem.countryname == pslrp.countryname)
            {
                foundit = 1;
            }
        });
        if (foundit == 0)
            dropdown.push(pslrp);

    });
});

it is not working.

3
  • 2
    "it is not working" — Define "not working". Give a clear problem statement. How does the behaviour you get differ from the behaviour you expect? Commented Feb 10, 2017 at 10:37
  • 1
    "convert jquery each function to pure javascript" — jQuery is pure JavaScript. There are perfectly valid reasons to want to remove a dependency on jQuery, but don't mistake jQuery for being anything other than JavaScript. Commented Feb 10, 2017 at 10:38
  • I have edited my question. Commented Feb 10, 2017 at 10:40

3 Answers 3

2

Note the difference in order of arguments in native forEach - first is the value of item, second is index. So instead of:

aslrp.forEach(function(index2, pslrp) {
...
dropdown.forEach(function(index3, dditem) {

use this:

aslrp.forEach(function(pslrp, index2) {
...
dropdown.forEach(function(dditem,index3) {
Sign up to request clarification or add additional context in comments.

Comments

2

You are using the .forEach() method wrong. forEach docs

You don't need to pass the array in as first argument. Just pass the callback.

dslr.forEach(function(dslrgp) {
  // do something..
}

or with key / value iteration

dslr.forEach(function(value, index) {
  // do something..
}

Comments

1

Your method signature is wrong. It's:

arr.forEach(function callback(currentValue, index, array) {
    //your iterator
}[, thisArg]);

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

1 Comment

what are arr, currentValue and array here ?

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.