create duplicate element and remove element javascript code example

Example 1: remove duplicates array javascript

var data = [1, 2, 'Peter', 3, 3,'Peter', 2, 2, 1, 2, 3, 4, 4, 5, 4];
var unique = data.filter((v, i, a) => a.indexOf(v) === i);

Example 2: remove duplicates array javascript

function uniqByKeepFirst(a, key) {
    let seen = new Set();
    return a.filter(item => {
        let k = key(item);
        return seen.has(k) ? false : seen.add(k);
    });
}


function uniqByKeepLast(a, key) {
    return [
        ...new Map(
            a.map(x => [key(x), x])
        ).values()
    ]
}

//

data = [
    {a:1, u:1},
    {a:2, u:2},
    {a:3, u:3},
    {a:4, u:1},
    {a:5, u:2},
    {a:6, u:3},
];

console.log(uniqByKeepFirst(data, it => it.u))
console.log(uniqByKeepLast(data, it => it.u))