Reputation: 49
I'm trying filter an array but it's returning empty, I'm trying to get it to return an array with where the date is in the previous 30 minutes and the value is over 15.
Let's say the current time is 19:45:
let transactions = [
{ value: "50.00", date: "2020-08-03T11:52:28.876Z" },
{ value: "13.10", date: "2020-08-03T11:57:32.900Z" },
{ value: "12.11", date: "2020-08-03T12:23:06.379Z" },
{ value: "12.89", date: "2020-08-03T14:20:41.720Z" },
{ value: "12.89", date: "2020-08-03T19:30:41.720Z" },
{ value: "22.89", date: "2020-08-03T19:34:41.720Z" },
{ value: "50.00", date: "2020-08-03T19:40:41.720Z" }
];
const THIRTY_MINUTES = 30 * 60 * 1000;
const isLastThirtyMins = transactions
.map(
transaction =>
new Date().getTime() - new Date(transaction.date).getTime() <
THIRTY_MINUTES
)
.filter(transaction => transaction.value >= 15);
console.log(isLastThirtyMins);
// []
I'm trying to get it to return these 2 items:
{ value: "22.89", date: "2020-08-03T19:34:41.720Z" }
{ value: "50.00", date: "2020-08-03T19:40:41.720Z" }
Upvotes: 0
Views: 92
Reputation: 1898
Use filter instead of map
const isLastThirtyMins = transactions
.filter(transaction => new Date().getTime() - new Date(transaction.date).getTime() < THIRTY_MINUTES)
.filter(transaction => parseFloat(transaction.value) >= 15);
Or better, call filter only once:
const isLastThirtyMins = transactions
.filter(transaction =>
(new Date().getTime() - new Date(transaction.date).getTime() < THIRTY_MINUTES) &&
(parseFloat(transaction.value) >= 15));
Upvotes: 1
Reputation: 1193
const isLastThirtyMins = transactions
.filter(
transaction =>
new Date().getTime() - new Date(transaction.date).getTime() <
THIRTY_MINUTES
);
Exaplaination:
What you where doing is mapping each element in you array to new Date().getTime() - new Date(transaction.date).getTime() < THIRTY_MINUTES
which is a boolean
. Thus, the return value of map
would be something like [true, false, false, true ...]
and then you are trying to filter this returned array by transaction.value
, but as you can see, transaction
now is a boolean and not the real transaction and it does not have value
property.
Upvotes: 0