I'm trying to filter out year out of this array of objects (in React)
2021-12-20,
2021-12-21,
2021-12-22,
(...)
2022-01-28,
2022-01-31,
2022-02-01,
It has 100 entries.
Anyways, this is what I have so far:
const stockDates = useMemo(() => chart && Object.keys(chart['Time Series (Daily)']).reverse(), [chart]);
let filtered = stockDates.replace(/2021-/g, ''); // or for 2022 /2022-/g
console.log(" no year: " filtered);
I'm getting undefined when console.logging 'filtered'
Any ideas on how to get rid of the year from date?
CodePudding user response:
Assuming these are date strings, you may use match
here:
stockDates = ['2021-12-20', '2021-12-21', '2021-12-22'];
years = stockDates.map(x => x.match(/\d{4}/)[0]);
console.log(years);
To remove the leading year, use:
stockDates = ['2021-12-20', '2021-12-21', '2021-12-22'];
years = stockDates.map(x => x.replace(/\d{4}-/, ""));
console.log(years);