Search code examples
javascriptmathgeojson

How to read a geojson file in javascript and get min or max of property?


I'm new to js sorry if it's a stupid question. I guess there is two parts to my question.

What is the simplest way to read a geojson file with javascript ?

Right now I'm using :

var centrisData = $.getJSON( "Path to geojson");

My file looks something like that:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {
        "type": "Maison\u00a0",
        "utilisation": "null",
        "piecesBeta": "20.0",
        "price": 3995000.0,
        "prixPiece_beta": 199750.0,
      },
    },
    {
      "type": "Feature",
      "properties": {
        "type": "Condo\u00a0",
        "utilisation": "null",
        "piecesBeta": "6.0",
        "price": 448900.0,
        "prixPiece_beta": 74816.67
      }
    }

I want to be able to get the min and max of the property "price". What would be the easiest way to do so ?

Thanks in advance !


Solution

  • You can loop over all of the features and keep and store the current minimum and maximum prices as variables.

    const centrisData = {
      "type": "FeatureCollection",
      "features": [{
          "type": "Feature",
          "properties": {
            "type": "Maison\u00a0",
            "utilisation": "null",
            "piecesBeta": "20.0",
            "price": 3995000.0,
            "prixPiece_beta": 199750.0,
          },
        },
        {
          "type": "Feature",
          "properties": {
            "type": "Condo\u00a0",
            "utilisation": "null",
            "piecesBeta": "6.0",
            "price": 448900.0,
            "prixPiece_beta": 74816.67
          }
        }
      ]
    };
    let min = Infinity, max = -min;
    for(const {properties: {price}} of centrisData.features){
      min = Math.min(min, price);
      max = Math.max(max, price);
    }
    console.log("Min:", min);
    console.log("Max:", max);