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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32432938/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 08:02:20  来源:igfitidea点击:

How to remove duplicate objects from JavaScript array in angularjs?

javascriptjavascript-objects

提问by durga siva kishore mopuru

This is my code

这是我的代码

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>';

OutPut

输出

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

In the above code I got unique objects from the JavaScript array, but i want to remove duplicate objects. So I want to get without duplicate objects from the array, the output like [ { "Id": "102", "name": "hari" }, { "Id": "104", "name": "ramesh" } ]

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

回答by Abbas Galiyakotwala

Check this

检查这个

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

回答by maxdec

This maybe? (not the most performant implementation but gets the job done):

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

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

Edit: faster method if the students are ordered by Id:

编辑:如果学生按 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);

回答by Varun

You can use javascript's filtermethod:

您可以使用 javascript 的filter方法:

The solution for the above problem can be found in thisfiddle. The performance of this solution will be better because we are using pure javascript and there is no third party overhead.

上述问题的解决方案可以在这个小提琴中找到。这个解决方案的性能会更好,因为我们使用的是纯 javascript 并且没有第三方开销。

app.controller('myCntrl',function($scope){

    var seen = {};
    //You can filter based on Id or Name based on the requirement
    var uniqueStudents = studentsList.filter(function(item){
    if(seen.hasOwnProperty(item.Id)){
        return false;
    }else{
        seen[item.Id] = true;
        return true;
    }
});
    $scope.students = uniqueStudents;

});

Let me know if you need any other details.

如果您需要任何其他详细信息,请告诉我。

回答by Mehdi Daustany

var unique = arr.filter(function(elem, index, self) {
    return index === self.indexOf(elem);
})

回答by Le Quang

You can use library lodashand method uniqBy()

您可以使用库lodash和方法uniqBy()

回答by Thinker

Here is the controller which will detect the duplicate element and remove it and will give you the element which has no duplicates. Just use this controller

这是控制器,它将检测重复元素并将其删除,并为您提供没有重复元素的元素。只需使用此控制器

$scope.names= studentsList.reduce(function(array, place) {
         if (array.indexOf( studentsList.name) < 0) 
                array.push( studentsList.name );
         else
                array.splice(array.indexOf( studentsList.name), 1);
         return array;
}, []);

Hope this works for your case

希望这适用于您的情况