Home > Software design >  Find the most recent date in a string and return a specific value associated with that date
Find the most recent date in a string and return a specific value associated with that date

Time:10-26

I have a string that contains a series of dates and other information. I want to identify the most recent date in the string and return the value for "Type of Check" associated with that date.

For the below example, the ideal output would be "Type of Check: Balance" since that is the most recent date in the string.

var myString = "Date: 04/08/2020,
Type of Check: Large,
Investors: ABC

 -- 

Date: 01/22/2021,
Type of Check: Debt,
Investors: ABC

 -- 

Date: 01/01/2022,
Type of Check: Balance,
Investors: ABC"

I have figured out how to identify the most recent date using the below code, but I have no idea how to return the "Type of Check" value associated with that date.

var dates = myString.match(/(\d{1,4}([.\-/])\d{1,2}([.\-/])\d{1,4})/g);

const descendingDateOrder = dates.sort((a, b) => {
    return new Date(b).getTime() - new Date(a).getTim

CodePudding user response:

All you have to do is to convert your string into an array, where each group of data is an individual member. Since you have a "delimiter" in your string, this is easy.

const myArray = myString.split("--");

You already have the most recent date figured out - descendingDateOrder[0]. Using this you could filter the array for the right group of data.

const match = myArray.filter(item => item.includes(descendingDateOrder[0]));

Remember, though, if you have multiple entries for the same date, you'll get them all here.

Now that you've got the matching group of data, a.k.a. string, since the pieces of data here are comma delimited, you can split it into an array of strings and get the desired text using its index.

const matchedTypeOfCheck = match[0].split(",")[1].trim();

The trim() method removes the leading and trailing whitspaces.

CodePudding user response:

Does it help you?

const input = `Date: 04/08/2020,
Type of Check: Large,
Investors: ABC

Date: 01/22/2021,
Type of Check: Debt,
Investors: ABC

Date: 01/01/2022,
Type of Check: Balance,
Investors: ABC`;

const getLatestDate = (input) => {
var dates = input.match(/(\d{1,4}([.\-/])\d{1,2}([.\-/])\d{1,4})/g);

const descendingDateOrder = dates.sort((a, b) => new Date(b).getTime() - new Date(a).getTime());

console.log(input.split('\n\n').find((some) => some.includes(descendingDateOrder[0])));
};


getLatestDate(input);

  • Related