简体   繁体   中英

Comparison logic less than but more than when initial value is indeterminate

The code below is a sliver of a larger project involving moment.js, but moment isn't necessary. I'm working in UTC dates and I can use a simple value comparison. I'm looking to return the index that value is after but is the lowest of all values (lower than uc). In other words, lowest value that is more than faketimenow . Since these values are out of order, they all need to be checked against the lowest value.

The code below works, but I'm curious if this can be built without a placeholder uc variable to store an initial starting variable. This would be easy if I was looking for greatest, but not certain how to compare against a value that has an indeterminate initial value. I tried using arr[0] as the starting value but that is passed through since its unluckily the least number.

// random range for demonstration purposes
var arr = [1, 2, 3, 4, 100, 17, 22, 15, 13, 11, 23];

var faketimenow = 10;

//initial index to use
var indextouse = 0;

// using a variable with initial start value that is ridiculously out of scope
var uc = 1000000000000;

for (i = 0; i < arr.length; i++) {
  console.log("i: " + i + " , faketimenow: " + faketimenow + " , indextouse: " + indextouse + ", uc: " + uc);
  if (arr[i] > faketimenow && arr[i] < uc) {
    uc = arr[i];
    indextouse = i;
  }
}

console.log(arr[indextouse]);

You can use Infinity as the initial value, everything is lower than that.

But a simpler solution is to sort the array and then find the first element higher than faketimenow .

 // random range for demonstration purposes var arr = [1, 2, 3, 4, 100, 17, 22, 15, 13, 11, 23]; var faketimenow = 10; arr.sort((a, b) => a - b); var uc = arr.find(n => n > faketimenow); console.log(uc);

You could take a single loop approach without sorting and return the index of the smallest value above the given value.

 var array = [1, 2, 3, 4, 100, 17, 22, 15, 13, 11, 23], value = 10, index = -1, i; for (i = 0; i < array.length; i++) { if (array[i] > value && (index === -1 || array[i] < array[index])) index = i; } console.log(array[index]);

With reduce .

 var array = [1, 2, 3, 4, 100, 17, 22, 15, 13, 11, 23], value = 10, index = array.reduce((r, v, i, a) => v > value && (r === -1 || v < a[r]) ? i : r, -1); console.log(array[index]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM