Get first positive integer in array

easy

By - Aman Pareek

Last Updated - 26/08/2024

Problem Statement

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

Example 1

Input: array = [-8, -6, 4, 6, 9, 3]

Output: 4

Solution 1: Using filter Method

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 

Solution 2: Using find Method

function findFirstPositiveFind(arr) {
  return arr.find(val => val > 0) ?? null;
} 

const array1 = [-8, -6, 4, 6, 9, 3];
findFirstPositiveFind(array1);  //output: 4 

Solution 3: Using map and filter

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 

Solution 4: Using Iterative for Loop

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 

Solution 5: Using forEach Method

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 

Solution 6: Using reduce Method

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 

Solution 7: Using some Method

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 

Solution 8: Using while Loop

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 

Resources

Popular Solutions