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

Remove duplicate values and overwrite the array

There is such an array:

[
    { message: '12949', author: 'esP' },
    { message: '1609', author: 'user' },
    { message: '1613', author: 'adm' },
    { message: '12949', author: 'Mdr' },
    { message: '12949', author: 'rood' }
]

How can you make sure that messages are not repeated, the authors are written separated by commas:

[
    { message: '12949', author: 'esP, Mdr, rood' },
    { message: '1609', author: 'user' },
    { message: '1613', author: 'adm' }
]

I check for uniqueness this way:

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 _ = require('underscore');
let a = _.uniq(arr, x => x.message)

What to do next? Create a second loop and compare values?

>Solution :

We can use Array.reduce(), to get the required result.

We’d add each item to a map object (accumulator), using the message value as the key, then use Object.values() to return our desired result array:

const arr = [ { message: '12949', author: 'esP' }, { message: '1609', author: 'user' }, { message: '1613', author: 'adm' }, { message: '12949', author: 'Mdr' }, { message: '12949', author: 'rood' } ];

const result = Object.values(arr.reduce((acc, { message, author }) => { 
    if (!acc[message]) {
        acc[message] = { message, author };
    } else {
        acc[message].author += `, ${author}`;
    }
    return acc;
}, {}));

console.log('Result:', result)
.as-console-wrapper { max-height: 100% !important; top: 0; }
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