Javascript function to try element in array if one was not found

1812 views javascript
2

I have the following js function in a React App that gets the county/district from google maps api result.

This works to get administrative_area_level_2. Right now if its not found, I just return unknown

    export const getDistrict = place => {
  var filtered_array = place.address_components.filter(function(address_component)
  {
    return address_component.types.includes('administrative_area_level_2')
  })
  var district = filtered_array.length ? filtered_array[0].long_name: 'Unknown'
  return district
}

The problem is that for some addresses, administrative_area_level_1 replaces administrative_area_level_2.. How to modify the above function to efficiently check for administrative_area_level_2 first and then if not present get administrative_area_level_1

Here is a sample api result:

{long_name: "Mumbai", short_name: "Mumbai", types: Array(2)}
1
:
long_name
:
"Mumbai"
short_name
:
"Mumbai"
types
:
(2) ["administrative_area_level_2", "political"]

answered question

2 Answers

6

.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';
};

posted this
2

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

posted this

Have an answer?

JD

Please login first before posting an answer.