Skip to content Skip to sidebar Skip to footer

Get Closest (but Higher) Number In An Array

I have a number say 165 I have an array with numbers in it. Like this: [2, 42, 82, 122, 162, 202, 242, 282, 322, 362] I want that the number I've got changes to the nearest, but hi

Solution 1:

Here's a method using Array.forEach():

const number = 165;
const candidates = [2, 42, 82, 122, 162, 202, 242, 282, 322, 362];

//looking for the lowest valid candidate, so start at infinity and work downlet bestCandidate = Infinity;

//only consider numbers higher than the targetconst higherCandidates = candidates.filter(candidate => candidate > number);

//loop through those numbers and check whether any of them are better than//our best candidate so far
higherCandidates.forEach(candidate => {
    if (candidate < bestCandidate) bestCandidate = candidate;
});

console.log(bestCandidate); //the answer, or Infinity if no valid answers exist

Solution 2:

You need sort array after a insert like this:

let list = [10, 20, 50];
let elementToInsert = 40;
list.push(elementToInsert);
list.sort(function(a, b) {
  return a - b;
});

Return must be [10, 20, 40, 50]

Solution 3:

You can accomplish this by sorting the array and the iterating over it to find the first value satisfying your condition:

constgetFirst = (arr, predicate) => {
  for (const val of arr) {
    if (predicate(val)) return val;
  }
  returnundefined;
}

const x = getFirst([2, 42, 82, 122, 162, 202, 242, 282, 322, 362].sort(), x => x > 165);

console.log(x);

Solution 4:

For you specific example:

vararray = [2, 42, 82, 122, 162, 202, 242, 282, 322, 362];
var found = array.find(function(element) {return element > 165;});

When you log found you will always get 202.

This will always return the first element greater than your number, which is logically closest and higher

Post a Comment for "Get Closest (but Higher) Number In An Array"