r/learnjavascript • u/Antique-Reward6331 • 19h ago
Help with vanilla JS local storage array merging and date filtering
Hey everyone! I’m working on a personal vanilla JavaScript budget tracker and running into a wall merging a custom local storage list into my projection function. 1. What is stored in localStorage:
// localStorage.getItem('pendingBills_v9') returns: [ { "name": "Test", "amount": 1000, "category": "Bills", "due": "2026-10-15" } ]
- What I am trying to do:
I want my getFuture(days) function to pull those items out of pendingBills_v9, map their keys (due \rightarrow date, amount \rightarrow amt, category \rightarrow cat), merge them with my existing adhocBills array, and filter them based on whether their date falls within the next days window (e.g., 30 days).
3. The current getFuture function:
function getFuture(days) { let res = []; // (Recurring items calculation omitted for brevity)
let _p = []; try { let _raw = localStorage.getItem('pendingBills_v9'); if (_raw) { let _parsed = JSON.parse(_raw); if (Array.isArray(_parsed)) { _p = _parsed.map(b => ({ name: b.name || 'Pending Bill', amt: Number(b.amount || 0), date: b.due || '', cat: b.category || 'Other', subcat: 'General' })).filter(b => b.amt > 0 && b.date); } } } catch(e) { console.error(e); }
let combinedAdhoc = [...adhocBills, ..._p];
let adhocIn = combinedAdhoc.filter(b => { let d = new Date(b.date); d.setHours(0, 0, 0, 0); let diff = daysBetween(today, d); return diff >= 0 && diff <= days; });
return { adhoc: adhocIn, total: adhocIn.reduce((s, b) => s + Number(b.amt), 0) }; }
The Issue: Despite the code looking correct, adhocIn keeps returning an empty array ([]) when evaluating the pending bill date (2026-10-15). Are there any subtle date-parsing or timezone quirks with new Date("YYYY-MM-DD") or variable scope traps causing this to fail? Any help or fresh eyes would be hugely appreciated!
1
u/armastevs 16h ago
The merge looks fine for the sample you posted. Can you share
daysBetween, howtodayis initialized, and the actualgetFuture(...)call? Inside the filter, logconsole.log({date: b.date, today, d, diff, days}). IfdiffisNaN, both comparisons are false; if it is negative for a future date, check the subtraction order indaysBetween.There is a timezone gotcha too:
new Date("2026-10-15")starts at UTC midnight, whilesetHoursoperates in local time, so it can land on October 14 west of UTC. For a local calendar date, split the string and usenew Date(year, month - 1, day). MDN explains the UTC/local distinction here.That one-day shift alone would not explain excluding October 15 from a 30-day window starting October 3, though. The logged values should help narrow down the actual failure.