从javascript中的多维数组对象中删除重复值的现有对象

时间:2015-08-06 15:32:45

标签: javascript arrays multidimensional-array

这是我的javascript数组:

 [{
     "id": "44",
     "name": "chathura"
 }, {
     "id": "45",
     "name": "gayan"
 }, {
     "id": "48",
     "name": "sunimal"
 }, {
     "id": "47",
     "name": "chathura"
 }, {
     "id": "20",
     "name": "yasith"
 }, {
     "id": "21",
     "name": "thisaru"
 }, {
     "id": "42",
     "name": "insaf"
 }, {
     "id": "63",
     "name": "sunimal"
 }, {
     "id": "78",
     "name": "yasith"
 }, {
     "id": "36",
     "name": "thisaru"
 }]

我想从此数组中删除重复名称的现有对象元素,并获取以下内容:

[{
    "id": "47",
    "name": "chathura"
}, {
    "id": "45",
    "name": "gayan"
}, {
    "id": "48",
    "name": "sunimal"
}, {
    "id ": "20",
    "name ": "yasith "
}, {
    "id ": "21 ",
    "name ": "thisaru"
}, {
    "id ": "42 ",
    "name ": "insaf"
}]

如何删除重复项?

2 个答案:

答案 0 :(得分:0)

您可以遍历数组并使用哈希表来过滤已使用的任何ID:

function getUniqueNames(nameObjects) {
  var existingIds = { };

  return nameObjects
    .filter(function(nameObject) {
      var id = nameObject.id;
      var alreadyExists = existingIds[id];
      existingIds[id] = true;
      return alreadyExists;
    });

我不确定您的用例,但在您的情况下将数据转换为Map可能是有意义的。地图的工作方式类似于哈希表,并将每个名称映射到其ID。它们通过设计强制实现独特性:

var names = nameObjects
  .reduce(function(map, nameObject) {
    map.set(nameObject.id, nameObject.name);
    return map;
  }, new Map());

// Look up a name by ID
names.get(47);

// Do something for every name
names.forEach(function(name, key) {
  console.info(name, 'has ID', key);
});

地图是ES6,某些浏览器可能需要polyfill

答案 1 :(得分:0)

使用 push 方法尝试此工作解决方案:

JS:

var arr = {};
for ( var i=0; i < x.length; i++ )
    arr[x[i]['name']] = x[i];

var result = new Array();
for ( var key in arr )
    result.push(arr[key]);

这将返回包含非重复对象的对象数组result

结果:

[{
    "id": "47",
    "name": "chathura"
}, {
    "id": "45",
    "name": "gayan"
}, {
    "id": "48",
    "name": "sunimal"
}, {
    "id ": "20",
    "name ": "yasith "
}, {
    "id ": "21 ",
    "name ": "thisaru"
}, {
    "id ": "42 ",
    "name ": "insaf"
}]

希望这会有所帮助。