Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get unique values from Object Array Javascript

So I have an object array that as follows:

var array = [
    {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 },
]

I want to filter data depending if the name, amount and date has duplicate. This one doesn't filter even a duplicate name.

var unique = array.filter((v, i, a) =>{ return a.indexOf(v) === i});

How can I filter duplicate for this one based on name, amount and date?

like image 824
Eem Jee Avatar asked Jul 26 '18 11:07

Eem Jee


2 Answers

Try this code it returns unique objects only.

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)

Do tell me if this is not what you're looking for.

like image 165
Syed Kashan Ali Avatar answered Oct 27 '22 03:10

Syed Kashan Ali


Just try this:

     var array = [
        {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 unique = Array.from(new Set(array.map(JSON.stringify))).map(JSON.parse);
    
    console.log(unique)
like image 24
mojtaba ramezani Avatar answered Oct 27 '22 01:10

mojtaba ramezani