Search code examples
javascriptamchartsamcharts4

How to display objects within an array if they have a certain value?


I am plotting cities on a map based on their object values.

I need to be able to have these plots hide or show based on their values.

So far, I have the following, which will toggle all cities on or off, as well as a function to log the cities if their values are <= 30.

var mapData = {
    'cities': [{"name":"Москва", "latitude":55.752, "longitude":37.615, "value":"10", "color": am4core.color("#ff0000")},
    {"name":"Старая Ладога", "latitude":60.0016, "longitude":32.2926, "value":"20", "color":chart.colors.getIndex(1)},
    {"name":"Великий Новгород", "latitude":58.33, "longitude":31.16, "value":"30", "color":chart.colors.getIndex(1)},
    {"name":"Белозерск", "latitude":60.02, "longitude":37.46, "value":"40", "color":chart.colors.getIndex(2)},
    {"name":"Изборск", "latitude":57.7082, "longitude":27.8609, "value":"50", "color":chart.colors.getIndex(3)}
]};

var imageSeries = chart.series.push(new am4maps.MapImageSeries());
    imageSeries.data = mapData.cities;
    imageSeries.dataFields.value = "value";

var imageTemplate = imageSeries.mapImages.template;
    imageTemplate.propertyFields.latitude = "latitude";
    imageTemplate.propertyFields.longitude = "longitude";
    imageTemplate.nonScaling = true

var circle = imageTemplate.createChild(am4core.Circle);
    circle.fillOpacity = 0.7;
    circle.propertyFields.fill = "color";
    circle.tooltipText = "{name}: [bold]{value}[/]";

imageSeries.heatRules.push({
    "target": circle,
    "property": "radius",
    "min": 4,
    "max": 4,
    "dataField": "value"
})




function toggleCities() {
    var series = imageSeries;
        if (series.isHiding || series.isHidden) {
        series.show();
    }
    else {
        series.hide();
    }
}

I'm not sure what I need to change in order to specify that only cities with a value of <= 30 should be plotted.


Solution

  • Array.prototype.filter will be what you are after:

    const filteredData = mapData.cities.filter(d => parseInt(d.value) <= 30);
    

    filter returns an array of elements in the initial array that return true from the function passed to filter().

    In your example, I think in function toggleCities() you will want to:

    imageSeries.data = filteredData;
    

    when you want the <= 30 to apply, and then

    imageSeries.data = mapData.cities;
    

    when you don't