Eliminating cross repeated elements in an array of objects

1

tHola capos del JS I have a terrible doubt and I would like you to guide me so that I can resolve it. I have the following arrangement of objects where I must eliminate the crossed elements between "from" and "to", which are repeated. In what way could you make the comparisons and then eliminate those elements?

arreglo = [
      {"from":"163-D","to":"1485-B"},
      {"from":"163-D","to":"1723-B"},
      {"from":"1-B","to":"201-B"}, 
      {"from":"1723-B","to":"1-B"},
      {"from":"1-B","to":"958-B"}, // elementos a eliminar
      {"from":"958-B","to":"1-B"} // elementos a eliminar
    ]

I hope you can guide me, thank you already: D

    
asked by Elleiton 11.10.2018 в 23:50
source

2 answers

1

You can use array.splice() like this:

arreglo = [
      {"from":"163-D","to":"1485-B"},
      {"from":"163-D","to":"1723-B"},
      {"from":"1-B","to":"201-B"}, 
      {"from":"1723-B","to":"1-B"},
      {"from":"1-B","to":"958-B"}, // elementos a eliminar
      {"from":"958-B","to":"1-B"} // elementos a eliminar
    ]
var index = 0;
arreglo.forEach(function(el) {
  for (var i=index + 1; i < arreglo.length; i++) {    
    if(el.from == arreglo[i].to && el.to == arreglo[i].from) {      
      arreglo.splice(index, 1);
      arreglo.splice(i-1, 1);
    }
  }
  index++;
});
console.log(arreglo);
    
answered by 12.10.2018 / 00:15
source
2

You can try with this code of% pure JavaScript .

a = [
  {"from":"163-D","to":"1485-B"},
  {"from":"163-D","to":"1723-B"},
  {"from":"1-B","to":"201-B"}, 
  {"from":"1723-B","to":"1-B"},
  {"from":"1-B","to":"958-B"}, // elementos a eliminar
  {"from":"958-B","to":"1-B"} // elementos a eliminar
];
function test(){
  for(var i = 0; i<= a.length-1; i++){
    for(var j = i; j > 0; j--){
      if(a[i].from === a[j].to && a[i].to === a[j].from){
        console.log('Posición : ' + j +'. From : '+ a[j].from + '. To : ' + a[j].to);
        console.log('Posición : ' + i +'. From : '+ a[i].from + '. To : ' + a[i].to);
        a.splice(i, 1);
        a.splice(j, 1);
        return false;
      }
    }
  }
}

test();
console.log(a.length);
console.log(a);
    
answered by 12.10.2018 в 00:28