Home > Blockchain >  Check two arrays not empty and not undefined
Check two arrays not empty and not undefined

Time:02-22

Suppose arr1 is of type number[] | undefined. Normally, to exclude either emptyness and undefined I simply do:

if (arr1)
  // Here arr1 has at least one element

However, suppose that there is also arr2 of type number[] | undefined. I would like to check both for not empty and not undefined (and also make sure that ts doesn't complain). However this behaves wierdly:

if (arr1 && arr2)
  // ???

It looks like arr1 && arr2 is not doing a boolean AND but instead is doing a kind of intersection between the two arrays.

How could I rewrite this simple if condition to achieve what I need?

CodePudding user response:

if (arr1)
 

Only checks if the array is defined (as !![] returns true, unlike !!'' which returns false)

Therefore arr1 && arr2 will return true when both array are defined, empty or not.

What you want is following :

arr1 && arr1.length && arr2 && arr2.length

CodePudding user response:

if (arr1?.length && arr2?.lenght) {
    // both arr1 and arr2 contain at least one element
}

arr1?.length returns the length of the array or null if arr1 is null.

Documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

CodePudding user response:

A user-defined type guard would work:

function isNotEmptyOrUndefined(a: number[] | undefined): a is [number, ...number[]] {
    return Boolean(a && a.length);
}

if (isNotEmptyOrUndefined(arr1) && isNotEmptyOrUndefined(arr2)) {
    // ...
}

docs

  • Related