Home > OS >  How to find a number just greater than given number in array
How to find a number just greater than given number in array

Time:05-27

Function to find the next larger number in an array(JavaScript).Array is unsorted.

function findJustBiggerNum(array,n){
                //your code here

    }

here is 'n' the number whose successor I want to find Suppose an array [5,9,8,1]

if n=5  answer will be ---> 9
if n=1  answer will be ---> 5
if n=9  answer will be --->null

I need u to build that function for me

CodePudding user response:

Use findIndex() to compare:

const array1 = [5,9,8,1];
function findJustBiggerNum(arr, numb){
 return arr.findIndex(e => e === numb) <= arr.findIndex(e => e === Math.max(...arr)) || null
}

console.log(findJustBiggerNum(array1, 8))

CodePudding user response:

Hope so the below code will work for you

var array = [3 , 6, 2, 56, 32, 5, 89, 32];

var largest= 0;

for (i=0; i<=largest;i  ){
    if (array[i]>largest) {
        var largest=array[i];
    }
}
  • Related