Jeya Suriya Muthumari
Jeya Suriya Muthumari

Reputation: 2021

JS: ObservableArray Filtering

I have one observableArray like below,

var details = ko.observableArray([]);
details = [
      { AccName: "Jane Doe", ExpDt: '2019-01-10', Contract: "Trial" },
      { AccName: "John", ExpDt: '2018-12-30', Contract:  "Licensed"},
      { AccName: "Doe", ExpDt: '2018-09-10', Contract:  "Trial"}
];

From this, I need to extract users based on ExpDt and Contract.

For Ex => ExpDt < today dt (2019-01-10) and having "trial" contract
Answer should be => Jane Doe

Please give me some suggestion on how to do it.

Upvotes: 0

Views: 37

Answers (1)

kockburn
kockburn

Reputation: 17626

Using Array#filter, destructuring, String#split, Spread operator and Date.UTC

const details=[{AccName:"Jane Doe",ExpDt:"2019-01-10",Contract:"Trial"},{AccName:"John",ExpDt:"2018-12-30",Contract:"Licensed"},{AccName:"Doe",ExpDt:"2018-09-10",Contract:"Trial"}];

const res = details.filter(({ExpDt, Contract})=>{
  const darr = ExpDt.split("-");
  //Date.UTC accepts months from 0 - 11
  darr[1] = darr[1] - 1;
  return Date.UTC(...darr) < Date.now() && Contract === "Trial";
})

console.log(res);

You get two results because Doe also fits the requirments:

ExpDt: 2018-09-10 < 2019-01-10
Contract: Trial === Trial

Upvotes: 1

Related Questions