最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Filter Array by date of last 12 months(year to date) - Stack Overflow

programmeradmin5浏览0评论

I have an array that I want to filter out results based on a year (past year only) from todays date. I have lodash and momentjs at my disposal so imagine using these to help acplish my goal. As below I only want to use .gameScore with a .reportDate within the last year.

My array looks like this... (so it should only return the first object as its within the year to date range)

0:{gameScore: "1", reportDate: "2018-05-09"} 
1:{gameScore: "3", reportDate: "2017-06-12"}

I am doing other things with the data that should e after the filter:

var result = _(observations)
.omitBy(x => x.gameScore === "NULL")
.map(observation => ({ ...observation, value: SCORES[observation.gameScore] }))
.value();

Appreciate any help. Thanks

I have an array that I want to filter out results based on a year (past year only) from todays date. I have lodash and momentjs at my disposal so imagine using these to help acplish my goal. As below I only want to use .gameScore with a .reportDate within the last year.

My array looks like this... (so it should only return the first object as its within the year to date range)

0:{gameScore: "1", reportDate: "2018-05-09"} 
1:{gameScore: "3", reportDate: "2017-06-12"}

I am doing other things with the data that should e after the filter:

var result = _(observations)
.omitBy(x => x.gameScore === "NULL")
.map(observation => ({ ...observation, value: SCORES[observation.gameScore] }))
.value();

Appreciate any help. Thanks

Share edited Jun 29, 2018 at 7:43 cнŝdk 32.2k7 gold badges60 silver badges80 bronze badges asked Jun 27, 2018 at 11:19 Tom RudgeTom Rudge 3,2729 gold badges55 silver badges104 bronze badges 4
  • you mean filter only the dates of this year ? – Muhammad Usman Commented Jun 27, 2018 at 11:21
  • A year from todays date e.g 27/06/2018 to 27/06/2017 – Tom Rudge Commented Jun 27, 2018 at 11:24
  • The problem starts with having the dates as string. If they were timestamps or ISO dates, you could simply use array.filter() with a given min and max. – Rob Commented Jun 27, 2018 at 11:27
  • @TomRudgeYou can do it by by paring respectively years, months then days to keep only the ones from the last year. Check my answer for further details. – cнŝdk Commented Jun 27, 2018 at 11:54
Add a ment  | 

5 Answers 5

Reset to default 2

Well you can use Array.filter() method and filter dates that are relevant, by paring respectively years, months then days.

var result = observations
  .filter(observation => {
    return (
        moment(observation.reportDate).year() == moment().subtract('years', 1).year() &&
        (moment(observation.reportDate).month() > moment().subtract('years', 1).month() ||
        moment(observation.reportDate).month() == moment().subtract('years', 1).month() &&
        moment(observation.reportDate).days() >= moment().subtract('years', 1).days())) 
          ||
        (moment(observation.reportDate).year() == moment().year() &&
        (moment(observation.reportDate).month() < moment().month() ||
        moment(observation.reportDate).month() == moment().month() &&
        moment(observation.reportDate).days() <= moment().days())
        );
  });

Demo:

var observations = [{
    gameScore: "1",
    reportDate: "2018-05-09"
  },
  {
    gameScore: "3",
    reportDate: "2017-06-12"
  }
];

var result = observations
  .filter(observation => {
    return (
        moment(observation.reportDate).year() == moment().subtract('years', 1).year() &&
        (moment(observation.reportDate).month() > moment().subtract('years', 1).month() ||
        moment(observation.reportDate).month() == moment().subtract('years', 1).month() &&
        moment(observation.reportDate).days() >= moment().subtract('years', 1).days())) 
          ||
        (moment(observation.reportDate).year() == moment().year() &&
        (moment(observation.reportDate).month() < moment().month() ||
        moment(observation.reportDate).month() == moment().month() &&
        moment(observation.reportDate).days() <= moment().days())
        );
  });

console.log(result);
<script src="https://rawgit./moment/moment/2.2.1/min/moment.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/lodash.js/4.17.10/lodash.core.js"></script>

You get get the date of last year. And then filter on that

like

var dates = [
{gameScore: "1", reportDate: "2018-05-09"},
{gameScore: "3", reportDate: "2017-06-12"}];

var date = new Date();
date.setFullYear(date.getFullYear() - 1);
date.setHours(0,0,0,0)

var filteredDates = dates.filter( o=> new Date(o.reportDate) >= date);

console.log(filteredDates)

To get the date of last yeah you can simply subtract from from year using and then .setFullYear and then simply pare the dates

First you'd have to get a moment object of your date, convert it to a unix timestamp and then pare it to the current time's timestamp.

var date = moment("29-06-1995").unix();
var current = moment().unix;
var difference = current - date;

Then you can see if the difference is larger than a year

if(difference >= 31556926) {
    return false;
} else {
    return true;
}

This condition will go in the callback for your array.filter()

Assuming observations contains those objects you can filter them like this:

var date = new Date();
date.setFullYear( date.getFullYear() - 1 );
observations.filter(x => {
    return new Date(x.reportDate) - date > 0;
});

Using momentjs it would be something like this:

_.filter(observations, o=> moment().add(-12, "months").isSameOrBefore(moment(o.reportDate)))

or this:

_.filter(observations, o=> !moment().add(-1, "year").isAfter(moment(o.reportDate)))

Note that isSameOrBefore has been added in momentjs v2.11.0. Since v2.0.0 there are separate function isSame and isBefore or you can negate isAfter. See more in docs.

var observations = [
{gameScore: "1", reportDate: "2018-05-09"},
{gameScore: "3", reportDate: "2017-06-12"}
];

var result = _.filter(observations, o=> moment().add(-12, "months").isSameOrBefore(moment(o.reportDate)));

console.log(result);

result = _.filter(observations, o=> !moment().add(-1, "year").isAfter(moment(o.reportDate)));

console.log(result);
<script src="https://rawgit./moment/moment/2.11.0/min/moment.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/lodash.js/4.17.10/lodash.core.js"></script>

发布评论

评论列表(0)

  1. 暂无评论