I have a React component that I'm using a dictionary inside of to compare against an API response for address state, and map only the states that are returned back as options in a dropdown.
This is the mapping function I'm using to create the array of returned states:
let activeStates = props.locations.map(x => ({abbr: x.address.state, name: states[x.address.state]as string}));
Against my dictionary which looks like this:
const states = {
AL: "Alabama",
AK: "Alaska",
AZ: "Arizona",
AR: "Arkansas",
CA: "California",
CO: "Colorado",
(all US states are included)
};
And that creates an array of all the location addresses in a response like this:
3:
abbr: "3"
name: {abbr: "TN", name: "Tennessee"}
__proto__: Object
4:
abbr: "4"
name: {abbr: "WI", name: "Wisconsin"}
__proto__: Object
5:
abbr: "5"
name: {abbr: "NC", name: "North Carolina"}
__proto__: Object
6:
abbr: "6"
name: {abbr: "NC", name: "North Carolina"}
That feeds my Component where I'm mapping the array to the dropdown:
<select value={state} onChange={handleStateChange}>
<option value={''}>All</option>
{activeStates.map((state) => (
<option value={state.abbr}>{state.name}</option>))}
</select>
I'm trying to write a function that works off of activeStates
to create a new array of only one of each state/abbreviation instead of producing duplicates. I know that because all of the values returned in that mapped array are considered unique I need to run an indexing function to get rid of the duplicates, but I'm not sure how.
So far I've used:
let statesObj = props.locations.reduce((acc, curr) => {
acc[curr.address.state] = states[curr.address.state];
return acc;
}, {});
let uniqueStates = Object.entries(statesObj).map(([abbr, name]) => ({abbr, name }));
let activeStates = props.locations.map(x => ({abbr: x.address.state, name: states[x.address.state]}));
let uniqueStates = new Set(activeStates);
let uniqueStatesArray = [...uniqueStates]
and
let activeStates = Array.from(new Set(props.locations.map(x => ({ abbr: x.address.state, name: states[x.address.state]})))
None of which have worked.