过滤对象数组,以使2个对象都不相同

时间:2019-10-30 22:50:09

标签: javascript arrays filter

我有以下数组。如果stct相同,则认为对象相同。例如,第一个对象和第三个对象具有相同的st和ct,因此应忽略(过滤掉)最终数组中的第三个对象。如何过滤此数组,以使两个对象都不相同,最好使用array.filter方法?我已经阅读了文档,但我只是不知道如何表达我想要的条件作为过滤器功能的条件。

[{
  "st": "2012",
  "id": "43",
  "ct": "1",
  "sd": "2"
},
{
  "st": "2015",
  "id": "45",
  "ct": "2",
  "sd": "2"
},
{
  "st":"2015",
  "id": "45",
  "ct": "2",
  "sd": "1"
},]

2 个答案:

答案 0 :(得分:-1)

您可以这样做:

let uniqueArray = array.filter((o, i, self) => {
    return self.findIndex(z => z.ct === o.ct && z.st === o.st) !== i;
});

答案 1 :(得分:-1)

var objects = [{
      "st":"2012",
      "id": "43",
      "ct": "1",
      "sd": "2"
    },
    {
      "st":"2015",
      "id": "453",
      "ct": "2",
      "sd": "2"
    },
    {
        "st":"2012", // this is a duplicate
        "ct":"1"
    }
];

// Using a Set to keep track of uniqueness avoids iterating through the
// entire array with methods like .findIndex()
var knownKeys = new Set();

var key;
var uniqueObjects = objects.filter(function(obj) {
    key = obj.st + obj.ct;
    return !knownKeys.has(key) && knownKeys.add(key);
});