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.
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');