Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic condition in IF statement

I want to make condition of if statement dynamically in javascript,

check my code

var t = ['b','a']
if(t[0] !== 'a' && t[1] !== 'a'){console.log('remaining element')}

here t might be vary at any time say t = ['b','a','c'] then I need to write if condition like this

if(t[0] !== 'a' && t[1] !== 'a' && t[2] !== 'a'){console.log('remaining element')}

How can I rewirte this code efficiently?

like image 639
user3002180 Avatar asked Feb 13 '23 12:02

user3002180


1 Answers

You can use Array.prototype.every like this

if (t.every(function(currentElement) { return currentElement !== "a"; })) {
    console.log('remaining element');
}

This works with arbitrary number of elements.

On older environments which do not support Array.prototype.every, you can use the plain for loop version

var flag = true;
for (var i = 0 ; i < t.length; i += 1) {
    if (t[i] === "a") {
        flag = false;
        break;
    }
}

if (flag) {
    console.log('remaining element');
}
like image 63
thefourtheye Avatar answered Feb 16 '23 01:02

thefourtheye