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

5

8

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]);
Inmost answered 7/1, 2021 at 6:45 Comment(0)
S
15

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.

Software answered 7/1, 2021 at 6:48 Comment(1)
This will not work if there is a null value before the first "hello". The correct answer is to use loose equality check "!=".Aperture
O
7

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

console.log(arr.find(el => el))
// or
console.log(arr.find(el => !!el))
Osrock answered 13/7, 2021 at 12:38 Comment(0)
B
4

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])
Bonheur answered 7/1, 2021 at 6:52 Comment(0)
P
0

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));
Polygraph answered 17/1, 2022 at 13:40 Comment(0)
A
0

If what you mean by "non-null" is not null and not undefined then the accepted answer is incorrect because it is using strict equality check and will include null values if they were present before the first "hello".

You should use loose equality check: (only one "=")

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

console.log(arr.find(el => el != null)) // "el != undefined" also works

Using != null will skip any null or undefined value until it finds a different value, in this case "hello".

Aperture answered 22/7 at 2:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.