Reputation: 15581
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]);
Upvotes: 8
Views: 18627
Reputation: 53
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".
Upvotes: 0
Reputation: 326
const arr = [undefined, null, 'hello', 'hello', 'hi'];
console.log(arr.find(el => el))
// or
console.log(arr.find(el => !!el))
Upvotes: 8
Reputation: 11001
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])
Upvotes: 4
Reputation: 606
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));
Upvotes: 0