简体   繁体   中英

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

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 .

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

 const arr = [undefined, null, 'hello', 'hello', 'hi']; console.log(arr.find(el => el)) // or console.log(arr.find(el => !!el))

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM