Home  >  Q&A  >  body text

Filtering arrays of objects based on properties: a guide

I have the following JavaScript array of real estate family objects:

var json = {
    'homes': [{
            "home_id": "1",
            "price": "925",
            "sqft": "1100",
            "num_of_beds": "2",
            "num_of_baths": "2.0",
        }, {
            "home_id": "2",
            "price": "1425",
            "sqft": "1900",
            "num_of_beds": "4",
            "num_of_baths": "2.5",
        },
        // ... (more homes) ...     
    ]
}

var xmlhttp = eval('(' + json + ')');
homes = xmlhttp.homes;

What I want to do is be able to perform a filter on the objects to return a subset of the "home" objects.

For example, I would like to be able to filter based on: price, sqft, num_of_beds, and num_of_baths.

How to do something like the following pseudocode in JavaScript:

var newArray = homes.filter(
    price <= 1000 & 
    sqft >= 500 & 
    num_of_beds >=2 & 
    num_of_baths >= 2.5 );

Please note that the syntax does not have to be exactly the same as above. This is just an example.

P粉087951442P粉087951442346 days ago694

reply all(2)I'll reply

  • P粉366946380

    P粉3669463802023-10-10 10:39:56

    I'm surprised no one posted a one line reply:

    const filteredHomes = json.homes.filter(x => x.price <= 1000 && x.sqft >= 500 && x.num_of_beds >=2 && x.num_of_baths >= 2.5);

    ...Just to make it easier for you to read:

    const filteredHomes = json.homes.filter( x => 
      x.price <= 1000 && 
      x.sqft >= 500 && 
      x.num_of_beds >=2 && 
      x.num_of_baths >= 2.5
    );

    reply
    0
  • P粉315680565

    P粉3156805652023-10-10 00:41:14

    You can use array.prototype.filtermethod:

    var newArray = homes.filter(function (el) {
      return el.price <= 1000 &&
             el.sqft >= 500 &&
             el.num_of_beds >=2 &&
             el.num_of_baths >= 2.5;
    });

    Example:

    var obj = {
        'homes': [{
                "home_id": "1",
                "price": "925",
                "sqft": "1100",
                "num_of_beds": "2",
                "num_of_baths": "2.0",
            }, {
                "home_id": "2",
                "price": "1425",
                "sqft": "1900",
                "num_of_beds": "4",
                "num_of_baths": "2.5",
            },
            // ... (more homes) ...     
        ]
    };
    // (Note that because `price` and such are given as strings in your object,
    // the below relies on the fact that <= and >= with a string and number
    // will coerce the string to a number before comparing.)
    var newArray = obj.homes.filter(function (el) {
      return el.price <= 1000 &&
             el.sqft >= 500 &&
             el.num_of_beds >= 2 &&
             el.num_of_baths >= 1.5; // Changed this so a home would match
    });
    console.log(newArray);

    reply
    0
  • Cancelreply