Deleting elements in an array

Viewed 90

I am working on an angular app. 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. 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. 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". How can I do that?

4 Answers

You can do this with several methods like filter,reduce,map etc... I create two example below.

First one is simple forEach method. In a loop filter if there is same Name element then push to new array

In second reduce method again filter element if there is same Name element then push to new array.

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

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. From 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');

Related