2

I have the following js function in a React App that gets the county/district

This works to get administrative_area_level_2.

    export const getDistrict = place => {
  var filtered_array = place.address_components.filter(function(address_component)
  {
    return address_component.types
  return district
}

How to modify the above function to efficiently check for administrative_2 first and then if not present get administrative_1

2 Answers 2

2

.filter doesn't make much sense here, because you don't need to create an intermediate array, you just need to find a value. You might use .find to return a administrative_area_level_2, if found, else an administrative_area_level_1, else unknown:

export const getDistrict = ({ address_components }) => {
  const lvl2 = address_components.find(({ types }) => types.includes('administrative_area_level_2'));
  if (lvl2) return lvl2.long_name;
  const lvl1 = address_components.find(({ types }) => types.includes('administrative_area_level_1'));
  return lvl1 ? lvl1.long_name : 'Unknown';
};

Or, to keep your code more DRY, abstract the .find and long_name access into a separate function:

const makeFindType = arr => levelNum => {
  const found = arr.find(({ types }) => types.includes('administrative_area_level_' + levelNum));
  if (found) return found.long_name;
};

export const getDistrict = ({ address_components }) => {
  const findType = makeFindType(address_components);
  return findType('2') || findType('1') || 'Unknown';
};
Sign up to request clarification or add additional context in comments.

Comments

-1

You could add the logic in the method to check first in administrative_area_level_1, if found return and stop the execution, If not continue the search in administrative_area_level_2

Comments

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.