hi image there are multile object in array data = [ { "cityName": "ACEVEDO",…
- 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
- Assistant
To remove duplicates from an array of objects in JavaScript based on specific properties (in your case,
stateCdandstateNm), you can use the following approach. This example assumes that you want to maintain the first occurrence of each unique combination ofstateCdandstateNm.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:
-
Mapping with a Key: We create a
Mapusing a combination ofstateCdandstateNmas the key. This ensures that only one entry for each unique combination is stored in the map. -
Array.from(): This converts the values of the map back into an array.
-
Output: The resulting
uniqueDatawill contain only the first occurrence of objects with uniquestateCdandstateNm.
Result
In this case, the output will contain the first occurrence of each unique pair. Objects with the same
stateCdandstateNmwill be removed from the array.Feel free to customize this as needed, depending on how you define "duplicates."
-