Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

convert array layout while removing duplicate values

I need to take serviceType from my array and convert it to the following layout keeping only the unique values.

[
{
"Label": "Cars Now"
"Value": "Cars Now"
},
{
"Label": "Vans Now"
"Value": "Vans Now"
},
]

I’ve got the unique values below, but I can’t work out how to convert it to the layout I need.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const inputArray = [
{
"serviceType": "Cars Now",
"applictionType": "Direct",
"wheelType": "4x4"
},
{
"serviceType": "Cars Now",
"applictionType": "web",
"wheelType": "2x4"
},
,
{
"serviceType": "Vans Now",
"applictionType": "Direct",
"wheelType": "2x4"
}
]

let tempArr = inputArray.map(row => row.serviceType) // map extracts the serviceType
           .filter(service => service); // filter removes any undefined/empty values

newServiceSet = [...new Set(tempArr)] // only keeps unique values

console.log(newServiceSet)

>Solution :

Turn the Set of serviceTypes into an an array of strings, then map to turn each string into an object. You also need to filter out the empty space in the array.

const inputArray = [
{
"serviceType": "Cars Now",
"applictionType": "Direct",
"wheelType": "4x4"
},
{
"serviceType": "Cars Now",
"applictionType": "web",
"wheelType": "2x4"
},
,
{
"serviceType": "Vans Now",
"applictionType": "Direct",
"wheelType": "2x4"
}
];
const serviceTypes = new Set(inputArray.filter(Boolean).map(({ serviceType }) => serviceType));
const output = [...serviceTypes].map(label => ({ label, value: label }));
console.log(output);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading