I have two array like this
const array1 = ['1','2','3'];
const array2 = [];
But it can be that array1 is emptyand second array2 have members, what i need is that i want to create getter to return me array that is not empty, something like this
get notEmptyArray(): string[] {
const array1 = ['1','2','3'];
const array2 = [];
return array1 or array2;
}
I know i can do it like
if (typeof array !== 'undefined' && array.length === 0) {
// the array is defined and has no elements
}
if (array && !array.length) {
// array is defined but has no element
}
But is there some simple inliner for that?
CodePudding user response:
Using a ternary operator (or two) could make your solution very concise. This will first check whether array1 has members and if so, return it. If not, it will check for array2 and return that or null (if it is also empty):
return array1 && array1.length ? array1 : array2 && array2.length ? array2 : null
