var arr = ["10/27/2017","11/5/2017","11/5/2017","11/10/2017","11/10/2017","12/12/2017"];
var userDate = "11/10/2017";
If I want to find a date in this (assume sorted) array that is right before the user date, how would I do so? So in this case, I'd like to return 11/5/2017.
Basically, finding the next closest object to the left of the designated date in the array. To take it one step further, if I wanted to then check again what the previous element was, but wanted to avoid duplicates, that would be helpful.
You can use Array#indexOf.
Don't forget to check if the element exists and isn't the first with arr.indexOf(userDate) > 0
let arr = ["10/27/2017","11/5/2017","11/10/2017","11/10/2017","12/12/2017"];
let userDate = "11/10/2017";
let result = arr.indexOf(userDate) > 0 ? arr[arr.indexOf(userDate) - 1] : null;
console.log(result);
Fairly simple using Array.indexOf
var arr = ["10/27/2017", "11/5/2017", "11/10/2017", "11/10/2017", "12/12/2017"];
var userDate = "11/10/2017";
var prev = arr.indexOf(userDate); // One call to indexOf - DRY
console.log(
prev > 0 ? // neither the first (==0) nor not found (==-1)
arr[prev-1] : "no earlier date"
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With