onmyway133 / blog

🍁 What you don't know is what you haven't learned
https://onmyway133.com/
MIT License
679 stars 33 forks source link

How to remove duplicates in Javascript array while keeping latest occurrence? #952

Open onmyway133 opened 1 year ago

onmyway133 commented 1 year ago

Use ES6 Map

The Map object holds key-value pairs and remembers the original insertion order of the keys. Any value (both objects and primitive values) may be used as either a key or a value.

type Deal = {
    name: string,
    link: string
}

removeDuplicates = (array: Deal[]) => {
    const map = new Map()
    array.forEach((item) => map.set(item.link, item))

    return [...map.values()]
}

We might need to update tsconfig.json

{
    "compilerOptions": {
        "target": "es6"
    }
}