Let's say I have an array of strings, and I need specific info from them, what would be an easy way to do that?
Suppose the array is this:
let infoArr = [
"1 Ben Howard 12/16/1988 apple",
"2 James Smith 1/10/1999 orange",
"3 Andy Bloss 10/25/1956 apple",
"4 Carrie Walters 8/20/1975 peach",
"5 Doug Jones 11/10/1975 peach"
];
Let's say I want to extract the date and save it into another array, well I could make a function like this
function extractDates(arr)
{
let dateRegex = /(\d{1,2}\/){2}\d{4}/g, dates = "";
let dateArr = [];
for(let i = 0; i<arr.length; i++)
{
dates = /(\d{1,2}\/){2}\d{4}/g.exec(arr[i])
dates.pop();
dateArr.push(dates);
}
return dateArr.flat();
}
Although this works, it is clunky and requires pop()
because it will return an array of arrays, ie: ["12/16/1988", "16/"]
, plus I need to call flat()
afterwards.
Another option would be to substring the strings, with a given position, where I need to know a regex pattern.
function extractDates2(arr)
{
let dates = [];
for(let i = 0; i<arr.length; i++)
{
let begin = regexIndexOf(arr[i], /(\d{1,2}\/){2}\d{4}/g);
let end = regexIndexOf(arr[i], /[0-9] /g, begin) + 1;
dates.push(arr[i].substring(begin, end));
}
return dates;
}
And of course it uses the next regexIndexOf()
function:
function regexIndexOf(str, regex, start = 0)
{
let indexOf = str.substring(start).search(regex);
indexOf = (indexOf >= 0) ? (indexOf + start) : -1;
return indexOf;
}
Again this function also works, but it seems too awful to accomplish the extraction of something simple. Is there an easier way to extract data into an array?