Created
April 24, 2018 00:09
-
-
Save keithws/050999285bf8c5d737c6c1776dda2054 to your computer and use it in GitHub Desktop.
Function to return the two letter state abbreviation from a US zip code.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function stateFromZIPCode (zipcode) { | |
var i, item, l, state, statesByZIP; | |
// list of zip code ranges and the states they reside in | |
statesByZIP = [ | |
[ 210, 3897, "NH" ], | |
[ 501, 544, "NY" ], | |
[ 1001, 5544, "MA" ], | |
[ 2801, 2940, "RI" ], | |
[ 3901, 4992, "ME" ], | |
[ 5001, 5907, "VT" ], | |
[ 6001, 6928, "CT" ], | |
[ 6390, 6390, "NY" ], | |
[ 7001, 8989, "NJ" ], | |
[ 10001, 14925, "NY" ], | |
[ 15001, 19640, "PA" ], | |
[ 19701, 19980, "DE" ], | |
[ 20101, 20199, "VA" ], | |
[ 20601, 21930, "MD" ], | |
[ 22002, 24658, "VA" ], | |
[ 24701, 26886, "WV" ], | |
[ 27006, 28909, "NC" ], | |
[ 29001, 29945, "SC" ], | |
[ 30002, 31999, "GA" ], | |
[ 32004, 34997, "FL" ], | |
[ 35004, 36925, "AL" ], | |
[ 37010, 38589, "TN" ], | |
[ 38601, 39776, "MS" ], | |
[ 39901, 39901, "GA" ], | |
[ 40003, 42788, "KY" ], | |
[ 43001, 45999, "OH" ], | |
[ 46001, 47997, "IN" ], | |
[ 48001, 49971, "MI" ], | |
[ 50001, 52809, "IA" ], | |
[ 53001, 54990, "WI" ], | |
[ 55001, 56763, "MN" ], | |
[ 57001, 57799, "SD" ], | |
[ 58001, 58856, "ND" ], | |
[ 59001, 59937, "MT" ], | |
[ 60001, 62999, "IL" ], | |
[ 63001, 65899, "MO" ], | |
[ 66002, 67954, "KS" ], | |
[ 68001, 69367, "NE" ], | |
[ 70001, 71497, "LA" ], | |
[ 71601, 72959, "AR" ], | |
[ 73001, 73199, "OK" ], | |
[ 73301, 73344, "TX" ], | |
[ 73401, 74966, "OK" ], | |
[ 75001, 79999, "TX" ], | |
[ 80001, 81658, "CO" ], | |
[ 82001, 83128, "WY" ], | |
[ 83201, 83888, "ID" ], | |
[ 84001, 84791, "UT" ], | |
[ 85001, 86556, "AZ" ], | |
[ 87001, 88441, "NM" ], | |
[ 88510, 88595, "TX" ], | |
[ 88901, 89883, "NV" ], | |
[ 90001, 96162, "CA" ], | |
[ 96701, 96898, "HI" ], | |
[ 97001, 97920, "OR" ], | |
[ 98001, 99403, "WA" ], | |
[ 99501, 99950, "AK" ] | |
]; | |
// ignore if zipcode is a string and is less than five characters | |
if (zipcode.length && zipcode.length < 5) { | |
return; | |
} | |
// only take the first five characters | |
if (zipcode.slice) { | |
zipcode = zipcode.slice(0, 6); | |
} | |
// convert from string to integer | |
zipcode = parseInt(zipcode, 10); | |
if (!isNaN(zipcode)) { | |
// zipcode is a number | |
// find the state which contains this zipcode | |
// use a for loop so we can break out | |
l = statesByZIP.length; | |
for (i = 0; i < l; i += 1) { | |
item = statesByZIP[i]; | |
if (zipcode >= item[0] && zipcode <= item[1]) { | |
state = item[2]; | |
break; | |
} | |
} | |
} | |
return state; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment