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


Solution 1:[1]

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.

Solution 2:[2]

Start with initial index as '0'

const arr = [undefined, undefined, 'hello', 'hello', 'hi'];
let index = 0;

while (!arr[index]) index++;

console.log(index, arr[index]);

Alternatively, use findIndex

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

const index = arr.findIndex(val => val);

console.log(index, arr[index])

Solution 3:[3]

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

console.log(arr.find(el => el))
// or
console.log(arr.find(el => !!el))

Solution 4:[4]

None of the posted answers are incorrect, however you may hit issues if ESLint is configured to watch arrow-parens (Airbnb rules adhere to this).

If you want to adhere to best practice, utilise one of the below (very minor modification to Psidom and Pavlov's answers).

const arr = [undefined, undefined, 'Item 1', 'Item 2', 'Item 3'];

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Psidom
Solution 2 Stephan
Solution 3 Stephan
Solution 4 Damian