Home > Software design >  Removing duplicates. generating new one and new key introduced on an array in javascript
Removing duplicates. generating new one and new key introduced on an array in javascript

Time:08-11

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:

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!

CodePudding user response:

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.

  • Related