Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JS call a different method on array depending on boolean

I have array var A = ['aa', 'bb', 'cc'];. If Boolean callFilter is true, I want to call .filter(x => x ==='bb') on it, if its false I want to call .concat('dd').
Is there a way other than

var result;
if(callFilter){
    result = A.filter(x=> x === 'bb');
} else {
    result = A.concat('dd');
}
console.log(result) // ['bb']

Id like to use ternary operation, but dont know if its possible to use it in form of

result = A[(callFilter) ? .filter(x => x === 'bb') : .concat('dd)]; // this doesnt work. 

Thanks!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

That is not possible. You can access a property conditionally, though that would require writing the condition twice in this case:

let result = A[callFilter ? 'filter' : 'concat'](callFilter ? x => x === 'bb' : 'dd');

It is better to just move the condition and repeat the variable A twice.

let result = callFilter ? A.filter(x => x === 'bb') : A.concat('dd');
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading