javascriptarraysreactjs

how to correctly map an obj and return a single value with several identical values ReactJS


I have an array of object

I map this table

[
 { id: "a", location: "FR", zone: "EU" } ,
 { id: "b", location: "FR", zone: "EU" } , 
 { id: "c", location: "ES", zone: "EU" } , 
 { id: "d", location: "ES", zone: "EU" } ,
]

to sort all the data I use a useEffect to retrieve only the values ​​I need

useEffect(() => {
    if (data) {
        const location = data.map((e) => {
            return {
                label: e.location,
            };
        });

        setLocations(locations);
    }
}, [data]);

this works correctly.

except which returns me the following format

0: {label: 'FR'}
1: {label: 'FR'}
2: {label: 'ES'}
4: {label: 'ES'}

and I would like to have the following format

  0: {label: 'FR'}
  1: {label: 'ES'}

basically it removes the identical key


Solution

  • Since you're using location as an id-like property that determines the uniqueness, you can do:

    const data = [
      { id: "a", location: "FR", zone: "EU" } ,
      { id: "b", location: "FR", zone: "EU" } , 
      { id: "c", location: "ES", zone: "EU" } , 
      { id: "d", location: "ES", zone: "EU" } ,
    ];
    
    console.log(
      Array
        .from(new Set(data.map(d => d.location)))  
        .map(label => ({ label }))
      
    )

    This first transforms the list to an array of strings. It uses a Set to get rid of duplicate strings. Then, it transforms to the desired output format.