Write a function to find the first positive integer in an array. If no positive integer is found, return null
.
Input: [-8, -6, 4, 6, 9, 3];
Output : 4
Input: array = [-8, -6, 4, 6, 9, 3]
Output: 4
function findFirstPositiveFilter(arr) {
const positives = arr.filter(val => val > 0);
return positives.length > 0 ? positives[0] : null;
}
const array1 = [-8, -6, 4, 6, 9, 3];
findFirstPositiveFilter(array1); //output: 4
function findFirstPositiveFind(arr) {
return arr.find(val => val > 0) ?? null;
}
const array1 = [-8, -6, 4, 6, 9, 3];
findFirstPositiveFind(array1); //output: 4
function findFirstPositiveMapFilter(arr) {
return arr.map(val => (val > 0 ? val : null)).filter(val => val !== null)[0] ?? null;
}
const array1 = [-8, -6, 4, 6, 9, 3];
findFirstPositiveMapFilter(array1); //output: 4
function findFirstPositiveForLoop(arr) {
for (const num of arr) {
if (num > 0) return num;
}
return null;
}
const array1 = [-8, -6, 4, 6, 9, 3];
findFirstPositiveForLoop(array1); //output: 4
function findFirstPositiveForEach(arr) {
let result = null;
arr.forEach(val => {
if (val > 0 && result === null) {
result = val;
}
});
return result;
}
const array1 = [-8, -6, 4, 6, 9, 3];
findFirstPositiveForEach(array1); //output: 4
function findFirstPositiveReduce(arr) {
return arr.reduce((firstPositive, val) => {
return firstPositive !== null ? firstPositive : (val > 0 ? val : null);
}, null);
}
const array1 = [-8, -6, 4, 6, 9, 3];
findFirstPositiveReduce(array1); //output: 4
function findFirstPositiveSome(arr) {
let result = null;
arr.some(val => {
if (val > 0) {
result = val;
return true;
}
return false;
});
return result;
}
const array1 = [-8, -6, 4, 6, 9, 3];
findFirstPositiveSome(array1); //output: 4
function findFirstPositiveWhileLoop(arr) {
let index = 0;
while (index < arr.length) {
if (arr[index] > 0) return arr[index];
index++;
}
return null;
}
const array1 = [-8, -6, 4, 6, 9, 3];
findFirstPositiveWhileLoop(array1); //output: 4