Last active
January 17, 2017 06:07
-
-
Save jdnichollsc/00ea8cf1204b17d9fb9a991fbd1dfee6 to your computer and use it in GitHub Desktop.
Filter arrays with lodash, sift.js, and other alternatives
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
_.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"} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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