2

I am relatively new to JS and would like to find the best method to set one variable equal to a subset of another variable another based on a dynamic condition.

In the example below,

  • clickedCode is a string that changes after each click event (all of the code below is within a click.event function).

  • features is an array of features with 400 elements, each containing a properties object which in turn contains elements such as latitude, longitude, etc.

  • cities is an empty array

          var clickedCode // dynamically changing string
          var cities = [];
          var features = map.queryRenderedFeatures({layers:['uni']});
    

for example, if I log some properties of the first feature, I will see:

var lon = features[0].properties.lon
var lat = features[0].properties.lat
var code = features[0].properties.code

console.log("" + lon + " " + lat + " " + code);

4.7005 50.8798 EMPHID

My objective is to subset features where features[i].properties.code is equal to clickedCode and then set cities equal to the resulting array so that roughly :

cities = features where features[i].properties.code === clickedCode

Any advice and explanation of structuring this in javascript would be helpful

3 Answers 3

4

You could use Array.filter()

So in your case it would be something like this:

var cities = features.filter(function (feature){
    return feature.properties.code === clickedCode;
});

By simply passing a callback function to the filter (be sure that the function returns a truthy/falsy value, otherwise you could get undesired behavior).

Sign up to request clarification or add additional context in comments.

Comments

1
cities = features.filter(function(t)
         {
           return t.properties  &&  // check is not null
                  t.properties.code === clickedCode;
         });

the inner function runs for each element of array and returns a bool.

true => return element

false => filter it

Comments

0

You can create a dictionary using code as key (I suppose it's unique) Then access to the clickedCode by through the dictionary's key

var data = {}
features.each((feature) => {
  data[feature.properties.code] = properties
  cities.push(feature.properties.code)
})
console.log(data[clickedCode])

You also you don't need cities anymore, because

cities = Object.keys(data)

2 Comments

code is not unique - there are multiple elements in features with the same code as clickedCode = my goal is to filter only those and create an array out of them
so the @Goliadkin solution is the best

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.