1

If a given array doesn't contain a given value, I wish to open a confirm dialog. The following works, however, my use of intermediate variable t seems a little excessive and I expect there is a more elegant way to do so. Could I return from the $.each loop and cause the upstream anonymous function to return false?

$(function(){
    myArr=[['de'],['df','de'],['df','dz'],['de']];
    if((function(){
        var t=true;
        $.each(myArr, function() {
            console.log($.inArray('de', this)=='-1');
            if($.inArray('de', this)=='-1') {t=false;return false;};    //Doesn't return true to parent
        })
        return t;
        })() || confirm("Continue even though one of the choices doesn't contain 'de'?") ){
        console.log('proceed');
    }
});
2
  • 1
    have a look at underscore. theres a lot of nice functions in ther! Commented Mar 14, 2015 at 15:36
  • myArr seems to looks just a normal javascript. Why don't you use javascript function ? myArray.forEach(function(element){ if(element.indexOf('de')) != -1 { confirm("....") } }); Commented Mar 14, 2015 at 15:39

3 Answers 3

3

You can use Array.prototype.some method, it will make code more comprehensive and simpler:

var myArr=[['de'],['df','de'],['df','dz'],['de']];

if (myArr.some(function(el) {
    return el.indexOf('de') === -1;
}) && confirm("Continue even though one of the choices doesn't contain 'de'?")) {
    document.write('proceed');
}

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks dfsq. Never knew about some before.
@DavidThomas I think that some is better, because it stops iterating once the first return el.indexOf('de') === -1 is true. At this point it doesn't matter anyway if other elements has de or not.
0

You could use grep instead, filtering out values that include 'de' and then counting the remaining:

$(function(){
    var myArr=[['de'],['df','de'],['df','dz'],['de']];
    var notDe = $.grep(myArr, function(item, index) {
            return ($.inArray('de', this)=='-1');
        });
    if(notDe.length == 0 || confirm("Continue even though one of the choices doesn't contain 'de'?") ){
        console.log('proceed');
    }
});

Comments

0

Another more readable solution:

$(function () {
    myArr = [
        ['de'],
        ['df', 'de'],
        ['df', 'dz'],
        ['de']
    ];

    var t = 0;
    $.each(myArr, function (k, v) {
        if ($.inArray('de', v) === -1) {
            t++;
        }
    });

    if (t > 0) {
        if (confirm("Continue even though " + t + " of the choices do not contain 'de'?")) {
            console.log('proceed');
        }
    }
});

Comments

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.