Home:ALL Converter>Google Apps Script: filter one 2D array based off the closest timestamp of another 2D array

Google Apps Script: filter one 2D array based off the closest timestamp of another 2D array

Ask Time:2021-04-29T13:03:19         Author:Matt Sinclair

Json Formatter

I have two 2D-arrays; both of which contain a timestamp and a float-value. Array1 contains hundreds of timestamp-value pairs, while Array2 will generally only contain ~10 timestamp-value pairs.

I am trying to compare Array1 with Array2, and only want to keep Array1's timestamp-value pairings for the timestamps that are closest to the timestamps in Array2.

Array1 = {[59.696, 2020-12-30T00:00:00.000Z], 
          [61.381, 2020-12-30T00:15:00.000Z], 
          [59.25, 2020-12-30T00:30:00.000Z],
          [57.313, 2020-12-30T00:45:00.000Z],...}

Array2 = {[78.210, 2020-12-30T00:06:00.000Z], 
          [116.32, 2020-12-30T00:39:00.000Z],...}

So in these Array examples above, I would want Array1 to be filtered down to:

Array1 = {[59.696, 2020-12-30T00:00:00.000Z], 
          [57.313, 2020-12-30T00:45:00.000Z],...}

because those timestamps are the closest match for timestamps in Array2. I have tried implementing the suggested code from Find matches for two columns on two sheets google script but can't get it to work, and I can't otherwise find a neat solution for the timestamp matching.

Any help is much appreciated. Let me know if I need to edit or add to my question with more information.

Author:Matt Sinclair,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/67311280/google-apps-script-filter-one-2d-array-based-off-the-closest-timestamp-of-anoth
yy