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

How to find unique value with id in JavaScript?

How to find unique value with id in JavaScript? right now I’m getting just value.

I’m getting:-

[
  "Care One",
  "Care Two"
]

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

[
{
    "Source_ID": 1,
    "SourceName_CR": "Care One"
},
{
    "Source_ID": 2,
    "SourceName_CR": "Care Two"
}

]

My code:-

const body = [
{
            Field_ID: 1,
            FieldName_CR: "First Name",
            Source_ID: 1,
            SourceName_CR: "Care One"
        },
        {
            Field_ID: 2,
            FieldName_CR: "Last Name",
            Source_ID: 1,
            SourceName_CR: "Care One"
        }, {
            Field_ID: 3,
            FieldName_CR: "Phone",
            Source_ID: 2,
            SourceName_CR: "Care Two"
        },
        {
            Field_ID: 4,
            FieldName_CR: "Email",
            Source_ID: 2,
            SourceName_CR: "Care Two"
        },  ];

console.log([...new Set(body.map(item => item.SourceName_CR))]);

>Solution :

A Set won’t work here because you want to deduplicate objects – but objects can’t be compared with each other that way. Doing just .map(item => item.SourceName_CR) doesn’t make sense either because then you only get the string (eg Care Two) and not the whole object you want.

Group the source names by the source IDs to deduplicate, then turn the entries of the resulting object into the required structure.

const body = [
{
    Field_ID: 1,
    FieldName_CR: "First Name",
    Source_ID: 1,
    SourceName_CR: "Care One"
},
{
    Field_ID: 2,
    FieldName_CR: "Last Name",
    Source_ID: 1,
    SourceName_CR: "Care One"
}, {
    Field_ID: 3,
    FieldName_CR: "Phone",
    Source_ID: 2,
    SourceName_CR: "Care Two"
},
{
    Field_ID: 4,
    FieldName_CR: "Email",
    Source_ID: 2,
    SourceName_CR: "Care Two"
},  ];
const namesBySourceID = Object.fromEntries(
  body.map(obj => [obj.Source_ID, obj.SourceName_CR])
);
const result = Object.entries(namesBySourceID)
  .map(([Source_ID, SourceName_CR]) => ({ Source_ID, SourceName_CR }));
console.log(result);
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