Mark Stone
Mark Stone

Reputation: 15

Javascript Logic to find greater number to match input

Actually I was working on a logic where I got an array and an input var, I need to compare that var with the array and find the smallest number in that array without using sorting, for eg. I got an array something like

const arr = [20,25,13,10,3,5,9,22];

and an input like

var inputt =3;

So I need to find the smallest number in array but greater then the input in the above situation the expected answer is " 5 ".

What should be the approach, I have tried performing a loop around the array and find the smallest number but cant figure out how to get the smallest number from an array which is greater then the input given.

var myarr = [5,3,9,10,7];
var smallest = arr[0];

for(var i=1; i<arr.length; i++){
    if(myarr[i] < smallest){
        smallest = myarr[i];   
    }
}

console.log(smallest);

Upvotes: 1

Views: 46

Answers (3)

row
row

Reputation: 190

You can also use reduce, this returns undefined if no matching number.

const res = arr.reduce((acc, v) => v > input && (acc === undefined || v < acc) ? v : acc, undefined);

Upvotes: 0

Kirit
Kirit

Reputation: 21

Try this, Let me know if it works

var myarr = [5,3,9,10,7];
var smallest = arr[0];

for(var i=1; i<arr.length; i++){
    if(myarr[i] < smallest){
        if( myarr[i] > inputt){
             smallest = myarr[i];  
        }
    }
}

console.log(smallest);

Upvotes: 0

benbotto
benbotto

Reputation: 2439

const arr = [20,25,13,10,3,5,9,22];
const input = 3;
const res = Math.min(...arr.filter(num => num > input));

console.log(res)

Filter out numbers that are less than the input, then find the min of those.

Upvotes: 2

Related Questions