Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find previous object in array [duplicate]

    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.

like image 602
jc1234 Avatar asked Aug 10 '26 04:08

jc1234


2 Answers

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);
like image 195
Zenoo Avatar answered Aug 11 '26 18:08

Zenoo


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"
);
like image 39
mplungjan Avatar answered Aug 11 '26 16:08

mplungjan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!