I have an arr
variable which looks as below:
JavaScript
x
2
1
const arr = [undefined, undefined, 'hello', 'hello', 'hi'];
2
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:
JavaScript
1
6
1
const arr = [undefined, undefined, 'hello', 'hello', 'hi'];
2
const index = arr.length;
3
4
while (index-- && !arr[index]);
5
6
console.log(arr[index]);
Advertisement
Answer
Just use find
:
JavaScript
1
3
1
const arr = [undefined, undefined, 'hello', 'hello', 'hi'];
2
3
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.