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

Removing duplicates. generating new one and new key introduced on an array in javascript

I have an array with a certain structure but I’m targetting a particular field value to check for occurrence in other items.

The array looks like this:

arr = [
       {'fruit': 'banana', 'code': 3},
       {'fruit': 'orange', 'code': 1},
       {'fruit': 'banana', 'code': 1},
       {'fruit': 'pineapple', 'code': 5}
]

Now the result I’m expecting is:

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

new_arr = [
       {'fruit': 'banana', 'code': 3, 'occurrence': 2},
       {'fruit': 'orange', 'code': 1, 'occurrence': 1},
       {'fruit': 'pineapple', 'code': 5, 'occurrence': 1}
]

The field I’m trying to target is ‘fruit’ checking for it occurrence and generating a new array with that occurrence.

This question might seem to be duplicated with some but no!

>Solution :

Here’s one way to do it using a Map object to keep track of dups for a given key and make the lookup for dups efficient. And, I’ve attempted to make it a generalized function that will work off any key of any array of objects:

const arr = [
    { 'fruit': 'banana', 'code': 3 },
    { 'fruit': 'orange', 'code': 1 },
    { 'fruit': 'banana', 'code': 3 },
    { 'fruit': 'pineapple', 'code': 5 }
];

function collectDups(array, key) {
    const items = new Map();
    for (const obj of array) {
        const prior = items.get(obj[key]);
        if (prior) {
            ++prior.occurrences;
        } else {
            items.set(obj[key], Object.assign({ occurrences: 1 }, obj))
        }
    }
    // convert back to array form
    return [...items.values()]
}

console.log(collectDups(arr, 'fruit'));

Note: This is a little more efficient than schemes that use .has() first because it only has to lookup a value once rather than .has() followed by .get().

Note: If code values are different for common fruit entries (as in your sample input), then this will set the code value to be the first one encountered in the array.

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