Answer the question
In order to leave comments, you need to log in
Check for entry into the range of numbers or if-hell?
How are such checks for occurrence in a certain interval of numbers or dates done correctly?
Let's say there are 500 some events, they have recorded time in unixtime. What is the best way to count and display events for the last 14 days from the current time?
So far I have only one idea
//создаем сразу массив с нужными данными
var datesArray = [];
var currentTime = Date.now;
var i = 13;
var timeInterval = 86400; //сутки
for(;i--;) {
datesArray.push( currentTime - timeInterval * i )
};
//и вторым циклом перебирать уже массив событий
i = 0
for(;i < events.length; i++) {
if (events.time >= datesArray[13] && events.time < datesArray[12] ) {
//событие было 13 дней назад
} else if (events.time >= datesArray[12] && events.time < datesArray[11] ) {
//событие было 12 дней назад
} else if ( events.time >= datesArray[11] && events.time < datesArray[10] ) {
//событие было 11 дней назад
};
//ну и так далее, думаю смысл понятен
}
Answer the question
In order to leave comments, you need to log in
moment.js will help you with dates.
Example:
var dates = [1520608921, 1520522534, 1512400948, 1521037358, 1521814967];
var fourteenDaysAgo = moment().subtract(14, 'days').format('X');
var filteredDates = dates.filter(function(date) {
return date > fourteenDaysAgo;
});
Where are you getting these events from?
If from the database, it can be easier to solve it (selection of events by date) at the request level to the database.
I would do something like this:
const events = [
{id:1, time: 10},
{id:2, time: 11},
{id:3, time: 15},
{id:4, time: 14},
{id:5, time: 13}
];
const bottom_limit = 11;
const result = events
.filter( event => event.time >= bottom_limit )
.sort( (first, second) => first.time - second.time );
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question