Shane Shane - 4 months ago 7
Javascript Question

Removing objects by date parameter.

How can i remove objects where

txnDate
is not from current start year
01/01/2016 till current date 08/05/2016.


[{
"site": "One",
"txnDate": "01/19/2015",
}, {
"site": "Two",
"txnDate": "01/25/2016",
}, {
"site": "Three",
"txnDate": "01/26/2014",
}, {
"site": "Three",
"txnDate": "09/05/2016",
}]


I want the array to contain only one object.

[{
"site": "Two",
"txnDate": "01/25/2016",
}]


I am not sure how to approach this, usually i do a filter by dateFrom and dateTo...

arr.filter(function (el) {
return el.txnDate <= "01/01/2016" &&
el.txnDate >= "08/05/2016";
});

Answer

You're almost there:

var arr = [{
    "site": "One",
    "txnDate": "01/19/2015",
   }, {
    "site": "Two",
    "txnDate": "01/25/2016",   
}, {
    "site": "Three",
    "txnDate": "01/26/2014",    
}, {
    "site": "Three",
    "txnDate": "09/05/2016",    
}];

var startTs = (new Date(new Date().getFullYear(), 0, 1)).getTime(),
    endTs = Date.now();

var res = arr.filter(function (el) {
  var ts = (new Date(el.txnDate)).getTime();
  return ts >= startTs && ts <= endTs;
});

console.log(res);