如何从对象数组 Javascript 中获取唯一值

2022-01-10 00:00:00 arrays duplicates 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 },
]

我想根据 nameamountdate 是否重复来过滤数据.这个甚至不过滤重复的名称.

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});

如何根据 nameamountdate 过滤重复项?

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

推荐答案

试试这个代码,它只返回唯一的对象.

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.

相关文章