Get unique object from array of object | unique object in array

If we have array of object and we want to find unique object from the array then it become tedious if we are not using/want any external library. Let try to code this requirement without using external library.

Solution 1:

var data = [
{name:"Joe", date:'2018-07-01', amt:250 },
{name:"Mars", date:'2018-07-01', amt:250 },
{name:"Joe", date:'2018-07-02', amt:250 },
{name:"Saturn", date:'2018-07-01', amt:250 },
{name:"Joe", date:'2018-07-02', amt:250 },
{name:"Jupiter", date:'2018-07-01', amt:250 },
]

var filtered = data.filter(function({name, date, amt}) {
    var key = `${name}${date}${amt}`;
    // Here is key does not exist in set then we will return true and add that key to set
    return !this.has(key) && this.add(key);
}, new Set);

console.log(filtered);

In above approach we combining all key value or we can required keys value. Here we want all three (name, date and amt) value should be unique so build a single string using value of all three keys and add in to set (which we are passing as argument in filter method).

If set has same key then we return false else true to filter condition.

Solution 2:

var data = [
{name:"Joe", date:'2018-07-01', amt:250 },
{name:"Mars", date:'2018-07-01', amt:250 },
{name:"Joe", date:'2018-07-02', amt:250 },
{name:"Saturn", date:'2018-07-01', amt:250 },
{name:"Joe", date:'2018-07-02', amt:250 },
{name:"Jupiter", date:'2018-07-01', amt:250 },
]
var resArr = [];
data.filter(function(item){
  var i = resArr.findIndex(x => (x.name == item.name && x.date == item.date && x.amt == item.amt));
  if(i <= -1){
        resArr.push(item);
  }
  return null;
});
console.log(resArr)

In above solution also we are using filter method but with findIndex method. In this approach we are maintaining a array. We are pushing the value to array if findIndex return negative value.

Leave a Reply