Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find first non null value in a typescript array?

I have an arr variable which looks as below:

const arr = [undefined, undefined, 'hello', 'hello', 'hi'];

I want to print out the first non-null value from within the arr array variable.

In above array, the output should be hello

I have written following logic but it is not giving the correct result:

const arr = [undefined, undefined, 'hello', 'hello', 'hi'];
const index = arr.length;

while (index-- && !arr[index]);

console.log(arr[index]);
like image 356
meallhour Avatar asked Jun 04 '26 23:06

meallhour


2 Answers

Just use find:

const arr = [undefined, undefined, 'hello', 'hello', 'hi'];

console.log(arr.find(el => el !== undefined))

It returns the value of the first element in the provided array that satisfies the provided testing function.

like image 60
Psidom Avatar answered Jun 07 '26 13:06

Psidom


const arr = [undefined, null, 'hello', 'hello', 'hi'];

console.log(arr.find(el => el))
// or
console.log(arr.find(el => !!el))
like image 42
Pavlo Maistruk Avatar answered Jun 07 '26 12:06

Pavlo Maistruk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!