Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-mini-2024-07-18· OpenAIAi2 WildChat-4.8M (AI2)

hi image there are multile object in array data = [ { "cityName": "ACEVEDO",…

  1. User

    hi image there are multile object in array data = [ { "cityName": "ACEVEDO", "fromPostalCd": "2717", "stateCd": "BS", "stateNm": "BS", "toPostalCd": "2717" } ]; remove duplicate from array with redundant stated and stateNm an

  2. Assistant

    To remove duplicates from an array of objects in JavaScript based on specific properties (in your case, stateCd and stateNm), you can use the following approach. This example assumes that you want to maintain the first occurrence of each unique combination of stateCd and stateNm.

    Here’s how you can achieve this:

    const data = [
        {
            "cityName": "ACEVEDO",
            "fromPostalCd": "2717",
            "stateCd": "BS",
            "stateNm": "BS",
            "toPostalCd": "2717"
        },
        {
            "cityName": "SOME CITY",
            "fromPostalCd": "2717",
            "stateCd": "BS",
            "stateNm": "BS",
            "toPostalCd": "2717"
        },
        {
            "cityName": "ANOTHER CITY",
            "fromPostalCd": "2717",
            "stateCd": "NY",
            "stateNm": "New York",
            "toPostalCd": "2718"
        }
    ];
    
    const uniqueData = Array.from(new Map(data.map(item => [`${item.stateCd}|${item.stateNm}`, item])).values());
    
    console.log(uniqueData);
    

    Explanation:

    1. Mapping with a Key: We create a Map using a combination of stateCd and stateNm as the key. This ensures that only one entry for each unique combination is stored in the map.

    2. Array.from(): This converts the values of the map back into an array.

    3. Output: The resulting uniqueData will contain only the first occurrence of objects with unique stateCd and stateNm.

    Result

    In this case, the output will contain the first occurrence of each unique pair. Objects with the same stateCd and stateNm will be removed from the array.

    Feel free to customize this as needed, depending on how you define "duplicates."