简体   繁体   English

删除数组中的元素

[英]Deleting elements in an array

I am working on an angular app.我正在开发 angular 应用程序。 I have an array "*identify duplicate" which is something like this.我有一个类似这样的数组“*识别重复”。

[
  {
   Name: "Jack",
   Id: "1"
  },
  {
    Name: "Rose",
    Id: "2"
  },
  {
    Name: "Jack",
    Id: "4"
  },
  {
    Name: "Jack",
    Id: "4"
  }
]

If I get same name and Id I want to remove both.如果我得到相同的名称和 ID,我想删除两者。 Like in above example in last two indexes name and Id are same "jack" But I don't want to delete any data if name is name and id is different.就像上面的例子一样,最后两个索引名称和 ID 是相同的“jack”但是如果名称是名称并且 id 不同,我不想删除任何数据。 Like in above example I want to keep Jack with Id "1" in my array but want to delete last two "Jack" with Id "4".就像上面的例子一样,我想在我的数组中保留 ID 为“1”的 Jack,但想删除 ID 为“4”的最后两个“Jack”。 How can I do that?我怎样才能做到这一点?

You can do this with several methods like filter,reduce,map etc... I create two example below.您可以使用过滤器、减少、map 等几种方法来做到这一点......我在下面创建了两个示例。

First one is simple forEach method.第一个是简单的 forEach 方法。 In a loop filter if there is same Name element then push to new array在循环过滤器中,如果存在相同的 Name 元素,则推送到新数组

In second reduce method again filter element if there is same Name element then push to new array.在第二个 reduce 方法中,如果存在相同的 Name 元素,则再次过滤元素,然后推送到新数组。

 var arr=[{Name: "Jack",Id: "1"},{Name: "Rose",Id: "2"},{Name: "Jack", Id: "4"},{Name: "Jack", Id: "4"}]; //simple foreach method var result=[]; arr.forEach(el=>{ if(result.filter(x=>x.Name==el.Name).length==0){result.push(el);} }); console.log(result); //reduce method var result2=arr.reduce((r, { Name, Id }) => { var temp = r.find(o => Name === o.Name); if (.temp) { r,push(temp = { Name; Id });} return r, }; []). console;log(result2);

Using Map()使用Map()

 var arr = [{Name:"Jack",Id:"1"},{Name:"Rose",Id:"2"},{Name:"Jack",Id:"4"},{Name:"Jack",Id:"4"}] let res = [...arr.reduce((a, i) => a.has(i.Name)? a: a.set(i.Name, i), new Map).values()] console.log(res)

Try this:尝试这个:

var a = [
{
 "Name": "Jack",
 "Id": "1"
},
{
  "Name": "Jack",
  "Id": "4"
},
{
  "Name": "Jack",
  "Id": "4"
}
]    
var jsonObject = a.map(JSON.stringify); 
console.log(jsonObject); 
var uniqueSet = new Set(jsonObject); 
var uniqueArray = Array.from(uniqueSet).map(JSON.parse); 
console.log(uniqueArray);

If you can use Javascript libraries such as underscore or lodash, I recommend having a look at _.uniq function in their libraries.如果您可以使用 Javascript 库,例如下划线或 lodash,我建议您在他们的库中查看 _.uniq function。 From lodash从 lodash

var arr=[ { Name: "Jack", Id: "1" }, { Name: "Rose", Id: "2" }, { Name: "Jack", Id: "4" }, { Name: "Jack", Id: "4" } ]; var updated_data = _.uniq(arr, 'Name');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM