I have a while loop that should iterate through an array and the selectedDate value to determine if an event will fall on the weekend coming, however it is not filtering out the results correctly and I am unsure why, everything looks correct to me. Is the while loop the correct tool for this sorting job?
Function
function(err,results) {
var i = results.length;
var theWeekend = [];
//console.log(results)
// EVERYTHING WORKS UNTIL HERE
while(i--) {
if (0 >= [friday, saturday, sunday].indexOf(results[i].selectedDate)) {
theWeekend.push(results[i]);
//console.log(theWeekend);
}
}
callback(err, theWeekend)
console.log(theWeekend);
}
The [friday, saturday, sunday] gives the correct dates to the console:
[ Fri Apr 08 2016 14:00:54 GMT+0100 (BST),
Sat Apr 09 2016 14:00:54 GMT+0100 (BST),
Sun Apr 10 2016 14:00:54 GMT+0100 (BST) ]
The anticipate result should be:
[ { _id: 570260718ef368db32c570c8,
url: 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators',
title: 'Expressions and operators - JavaScript | MDN',
selectedDate: Sun Apr 10 2016 01:00:00 GMT+0100 (BST),
__v: 0 } ]
However I am receiving data that has the previous weekend, which should be omitted:
[ { _id: 56fffb5ceb76276c8f39e3f3,
url: 'http://londonist.com/2015/11/where-to-eat-and-drink-in-balham',
title: 'Where To Eat And Drink In... Balham | Londonist',
selectedDate: Fri Apr 01 2016 01:00:00 GMT+0100 (BST),
__v: 0 },
{ _id: 570260738ef368db32c570c9,
url: 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators',
title: 'Expressions and operators - JavaScript | MDN',
selectedDate: Sun Apr 10 2016 01:00:00 GMT+0100 (BST),
__v: 0 },
{ _id: 56fffb8eeb76276c8f39e3f5,
url: 'https://news.ycombinator.com/item?id=11404770',
title: 'The Trouble with CloudFlare | Hacker News',
selectedDate: Sun Apr 03 2016 01:00:00 GMT+0100 (BST),
__v: 0 },
{ _id: 56fffb6ceb76276c8f39e3f4,
url: 'http://wellnessmama.com/13700/benefits-coconut-oil-pets/',
title: 'Benefits of Coconut Oil for Pets - Wellness Mama',
selectedDate: Sat Apr 02 2016 01:00:00 GMT+0100 (BST),
__v: 0 } ]
indexOffunction since you are trying to compare date objects, i.e. there's no way that any of them will match even if they point at the same date because these are different objects in memory.