Hala El Barchah Hala El Barchah - 3 months ago 9
AngularJS Question

Javascript, remove property from one of two similar objects in array

Let's assume we have this data set:

var array = [
{

"name": "a",
"group": "a"
},
{
"name": "a",
"group": "a"
},{
"name": "b",
"group": "b"
},
{
"name": "b",
"group": "b"
},
{
"name": "c"
}
];


and I want to loop through the array to see if there are two objects have the same group value, then remove the second of them.

for(var i = 0 ; i<array.length;i++){
var a = array[i];
for(var j = 0; j< array.length;j++){
if(array[j].group == a.group){
var b = array[j];
// I need code here to remove property "group" from the variable b only
break;
}
}
}


the final results I want are:

var array2 = [
{
"name": "a",
"group": "a"
},
{
"name": "a"
},{
"name": "b",
"group": "b"
},
{
"name": "b"
},{
"name":"c"
}
];


NOTE: I tried
delete array[j].group
but it caused to remove both
group
property from both equal objects. How can I solve that?

Answer

You shouldn't compare same items, just shift indexes in inner loop:

 var array = [{"name": "a", "group": "a"},
             {"name": "a", "group": "a"},
             {"name": "b", "group": "b"},
             {"name": "b", "group": "b"},
             {"name": "c"}];


for(var i = 0 ; i < array.length - 1; i++){
  var a = array[i];
  if(!a.group){
    continue;
  }

  for(var j = i+1; j < array.length; j++){
    var b = array[j];
    if(b.group === a.group){
      delete b.group;
    }
  }
}

console.log(array)

Comments