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

Javasript, remove ALL, REALLY ALL duplicates from object

Have object with notes, time entries, want to remove ALL (ALL, sorry for repeating this part, I’ve went through many examples and they all remove second, third etc duplicate only, but they include first duplicate) notes with same time DUPLICATES from it.

Well I need to separate unique from duplicates, I’ve managed to get all duplicates from it with this code I found here on StackOverflow,

const allNotes = [
    {
        "note": 69,
        "time": 0
    },
    {
        "note": 57,
        "time": 0
    },
    {
        "note": 60,
        "time": 1.5
    },
    {
        "note": 64,
        "time": 2
    },
    {
        "note": 69,
        "time": 2.5
    },
    {
        "note": 71,
        "time": 3
    },
    {
        "note": 52,
        "time": 3
    },
    {
        "note": 64,
        "time": 4.5
    },
    {
        "note": 68,
        "time": 5
    },
    {
        "note": 71,
        "time": 5.5
    }
]

const getDuplicates = () => {
const values = allNotes;
const unique = new Object;
const lookup = values.reduce((a, e) => {
  a[e.time] = ++a[e.time] || 0;
  return a;
}, {});
const duplicates = values.filter(e => lookup[e.time]);
console.log(duplicates);
}

And this code works like charm it produces

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

[
    {
        "note": 69,
        "time": 0
    },
    {
        "note": 57,
        "time": 0
    },
    {
        "note": 71,
        "time": 3
    },
    {
        "note": 52,
        "time": 3
    }
]

Still need to be able to get only unique time entries, need this result

[
    {
        "note": 60,
        "time": 1.5
    },
    {
        "note": 64,
        "time": 2
    },
    {
        "note": 69,
        "time": 2.5
    },
    {
        "note": 64,
        "time": 4.5
    },
    {
        "note": 68,
        "time": 5
    },
    {
        "note": 71,
        "time": 5.5
    }
]

>Solution :

You’ve already solved your problem since you’re able to pick out the duplicates. Just filter the opposite.

const uniqueValues = values.filter(e => !lookup[e.time]);
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