Azhar Ali Azhar Ali - 4 months ago 11
Javascript Question

How to get unique Id for multiple duplicate properties

say we have a object:

var db = [
{Id: "201" , Player: "Jon",price: "3.99", loc: "NJ" },
{Id: "202", Player: "Sam",price: "4.22", loc: "PA" },
{Id: "203" ,Player: "Sam",price: "4.22", loc: "NY" },
{Id: "204", Player: "Bill",price: "3.22", loc: "TX" },
{Id: "205" ,Player: "Dave",price: "3.99", loc: "WA" },
{Id: "206" ,Player: "Dave",price: "3.99", loc: "WI" },
];


202&203 and 205&206 have similar values for player and price but I need just one id for similar values i.e, output should be 202,205.

Can someone help me with that.

Answer

You could filter it with a hash table for look up for the same player and price values.

var db = [{ Id: "201", Player: "Jon", price: "3.99", loc: "NJ" }, { Id: "202", Player: "Sam", price: "4.22", loc: "PA" }, { Id: "203", Player: "Sam", price: "4.22", loc: "NY" }, { Id: "204", Player: "Bill", price: "3.22", loc: "TX" }, { Id: "205", Player: "Dave", price: "3.99", loc: "WA" }, { Id: "206", Player: "Dave", price: "3.99", loc: "WI" }],
    filtered = db.filter(function (a) {
        var key = a.Player + '|' + a.price;
        if (!this[key]) {
            this[key] = true;
            return true;
        }
    }, Object.create(null))

console.log(filtered);

Comments