如何从angularjs中的JavaScript数组中删除重复的对象?

dur*_*uru 12 javascript javascript-objects

这是我的代码

var studentsList = [
    {"Id": "101", "name": "siva"},
    {"Id": "101", "name": "siva"},
    {"Id": "102", "name": "hari"},
    {"Id": "103", "name": "rajesh"},
    {"Id": "103", "name": "rajesh"},
    {"Id": "104", "name": "ramesh"},
];

function arrUnique(arr) {
    var cleaned = [];
    studentsList.forEach(function(itm) {
        var unique = true;
        cleaned.forEach(function(itm2) {
            if (_.isEqual(itm, itm2)) unique = false;
        });
        if (unique)  cleaned.push(itm);
    });
    return cleaned;
}

var uniqueStandards = arrUnique(studentsList);

document.body.innerHTML = '<pre>' + JSON.stringify(uniqueStandards, null, 4) + '</pre>';
Run Code Online (Sandbox Code Playgroud)

产量

[
{
    "Id": "101",
    "name": "siva"
},
{
    "Id": "102",
    "name": "hari"
},
{
    "Id": "103",
    "name": "rajesh"
},
{
    "Id": "104",
    "name": "ramesh"
}
]
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,我从JavaScript数组中获取了唯一的对象,但我想删除重复的对象.所以我想从数组中得到没有重复的对象,输出如[{"Id":"102","name":"hari"},{"Id":"104","name":"ramesh" }]

Abb*_*ala 16

检查一下

    var uniqueStandards = UniqueArraybyId(studentsList ,"id");

    function UniqueArraybyId(collection, keyname) {
              var output = [], 
                  keys = [];

              angular.forEach(collection, function(item) {
                  var key = item[keyname];
                  if(keys.indexOf(key) === -1) {
                      keys.push(key);
                      output.push(item);
                  }
              });
        return output;
   };
Run Code Online (Sandbox Code Playgroud)


max*_*dec 4

这也许?(不是性能最好的实现,但完成了工作):

var studentsList = [
  {Id: "101", name: "siva"},
  {Id: "101", name: "siva"},
  {Id: "102", name: "hari"},
  {Id: "103", name: "rajesh"},
  {Id: "103", name: "rajesh"},
  {Id: "104", name: "ramesh"},
];

var ids = {};

studentsList.forEach(function (student) {
  ids[student.Id] = (ids[student.Id] || 0) + 1;
});

var output = [];
studentsList.forEach(function (student) {
  if (ids[student.Id] === 1) output.push(student);
});

console.log(output);
Run Code Online (Sandbox Code Playgroud)

编辑:如果学生按 Id 排序,则更快的方法:

var studentsList = [
  {Id: "101", name: "siva"},
  {Id: "101", name: "siva"},
  {Id: "102", name: "hari"},
  {Id: "103", name: "rajesh"},
  {Id: "103", name: "rajesh"},
  {Id: "104", name: "ramesh"},
];

var output = [];
studentsList.reduce(function (isDup, student, index) {
  var nextStudent = studentsList[index + 1];
  if (nextStudent && student.Id === nextStudent.Id) {
    return true;
  } else if (isDup) {
    return false;
  } else {
    output.push(student);
  }

  return false;
}, false);

console.log(output);
Run Code Online (Sandbox Code Playgroud)