habibg
habibg

Reputation: 185

Filter an array of objects in javascript

I would like to filter JavaScript objects by their property value. Here is a scenario:

The array below is a small example of what I'm working with

 var array = [{

    "Title": "July 13 - July 19 2014",
    "displayAd_imp": "15,242,505",
    "Date": "2014-07-17T00:00:00.000Z",
    "WeekNo": 29
}, {

    "Title": "July 20 - July 26 2014",
    "displayAd_imp": "15,942,705",
    "Date": "2014-07-24T00:00:00.000Z",
    "WeekNo": 30
}, {

    "Title": "July 27 - Aug 2 2014",
    "displayAd_imp": "15,683,545",
    "Date": "2014-07-31T00:00:00.000Z",
    "WeekNo": 31
}, {

    "Title": "Aug 3 - Aug 9 2014",
    "displayAd_imp": "15,042,005",
    "Date": "2014-08-07T00:00:00.000Z",
    "WeekNo": 32
}, {

    "Title": "Aug 10 - Aug 17 2014",
    "displayAd_imp": "15,442,605",
    "Date": "2014-08-14T00:00:00.000Z",
    "WeekNo": 33
}]

In my app there are two dropdown fields that would let users pick a range of weeks. I'm calculating the week number by the "Date" and inserting the "WeekNo" as a property. I would like to use WeekNo to get a chunk of data based on the start-end values.

Example would be if start date is week29 and end is week32 the method would return the relevant data.

I have a Jsfiddle going if someone would like to update it.

Thanks a ton in advance!

Upvotes: 0

Views: 91

Answers (2)

Parth Raval
Parth Raval

Reputation: 4413

 var array = [{
     "Title": "July 13 - July 19 2014",
     "displayAd_imp": "15,242,505",
     "Date": "2014-07-17T00:00:00.000Z",
     "WeekNo": 29
 }, {
     "Title": "July 20 - July 26 2014",
     "displayAd_imp": "15,942,705",
     "Date": "2014-07-24T00:00:00.000Z",
     "WeekNo": 30
 }, {
     "Title": "July 27 - Aug 2 2014",
     "displayAd_imp": "15,683,545",
     "Date": "2014-07-31T00:00:00.000Z",
     "WeekNo": 31
 }, {
     "Title": "Aug 3 - Aug 9 2014",
     "displayAd_imp": "15,042,005",
     "Date": "2014-08-07T00:00:00.000Z",
     "WeekNo": 32
 }, {

     "Title": "Aug 10 - Aug 17 2014",
     "displayAd_imp": "15,442,605",
     "Date": "2014-08-14T00:00:00.000Z",
     "WeekNo": 33
 }]

 var predicate = function(start, end) {
     return function(array) {
         return _.inRange(array.WeekNo, start, end + 1);
     }
 }

 var result = _.filter(array, predicate(29, 32));

 console.log('inRange', result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js"></script>

Upvotes: 0

Mike Cluck
Mike Cluck

Reputation: 32511

You can use the Array.filter function. You call it directly on your array then provide a callback. If that callback returns true, the element is included in a new array that's returned from filter.

For example:

var newArr = array.filter(function(item) {
    return (item.WeekNo >= 29 && item.WeekNo < 32);
});

Here's an updated JSfiddle with this included.

Upvotes: 3

Related Questions