Skip to content

Instantly share code, notes, and snippets.

@jdnichollsc
Last active January 17, 2017 06:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jdnichollsc/00ea8cf1204b17d9fb9a991fbd1dfee6 to your computer and use it in GitHub Desktop.
Save jdnichollsc/00ea8cf1204b17d9fb9a991fbd1dfee6 to your computer and use it in GitHub Desktop.
Filter arrays with lodash, sift.js, and other alternatives
//pretty printing JSON => JSON.stringify(obj, null, 2);
var product = {
"productTypeCode": "productTypeEnergy",
"quantities": [
{
"period": {
"startDate": new Date("2017-01-13T05:00:00.000Z"),
"endDate": new Date("2017-01-31T05:00:00.000Z"),
"dayType": {
"normal": true,
"holiday": true
},
"specificDays": [
"monday",
"wednesday",
"friday"
],
"loadType": {
"high": true,
"medium": false,
"low": false
}
},
"type": "DemandPercentage",
"quantityValue": "44"
},
{
"period": {
"startDate": new Date("2017-01-13T05:00:00.000Z"),
"endDate": new Date("2017-01-31T05:00:00.000Z"),
"dayType": {
"normal": true,
"holiday": true
},
"loadType": {
"high": false,
"medium": true,
"low": false
}
},
"type": "Value",
"quantityValue": "22"
}
]
};
var period = {
"startDate": new Date("2017-01-08T05:00:00.000Z"),
"endDate": new Date("2017-01-29T05:00:00.000Z"),
"dayType": {
"normal": true,
"holiday": true
},
"loadType": {
"high": true,
"medium": false,
"low": true
},
specificPeriods : ["3", "4", "5-10"]
};
//TODO:
//Find by date range where => a <= endDate && b >= startDate
startDate endDate
//1) --|-----------|--
a b
//2) -----|-----------|-----
a b
//3) -----|-----------|-----
a b
//4) -----|-----------|-----
a b
_.filter(product.quantities, (q) => {
if(!(period.startDate <= q.period.endDate && period.endDate >= q.period.startDate))
return false;
return true;
});
//Object {period: Object, type: "DemandPercentage", quantityValue: "44"}
sift({
$and: [
{ 'period.startDate': { $lte : period.endDate } },
{ 'period.endDate': { $gte : period.startDate } }
]
}, product.quantities);
//[]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment