0

I have the following Json object -

"links": [  
      {  
         "source":"1",
         "target":"2"
      },
      {  
         "source":"3",
         "target":"4"
      },
      {  
         "source":"5",
         "target":"6"
      },
      {  
         "source":"1",
         "target":"2"
      }
   ]

How can I remove a link if it already exists e.g. in the aforementioned Json -

  {  
     "source":"1",
     "target":"2"
  }

Exists twice so in this instance remove the duplicate where source and target match another link exactly.

I have tried -

var temp = [];

$.each(data.links, function (index, value) {
    if ($.inArray(value, temp) === -1) {
        temp.push(value);
    }
});

However temp ends up with the same amount of links as previous?

Ebikeneser
  • 2,530
  • 12
  • 48
  • 101

2 Answers2

1

Try my easy way:

var links = [  
      {  
         "source":"1",
         "target":"2"
      },
      {  
         "source":"3",
         "target":"4"
      },
      {  
         "source":"5",
         "target":"6"
      },
      {  
         "source":"1",
         "target":"2"
      }
   ];
var temp = [];
$.each(links, function (index, value) {
    if (!temp[value.source + value.target]) {
        temp[value.source + value.target] = value;      
    }
});
console.log(temp);
Thi Tran
  • 641
  • 4
  • 11
0

inArray does not compare properties, in this case it probably checks if reference object is the same

You have two ways of comparing, you can compare JSON.stringify version of an object. Or you can compare by properties. I will provide example in a moment of both cases.

Example with stringify:

_.uniq(links, JSON.stringify)

with lodash/underscore

And example of comparing properties

_.each(links, function(link) {
    if (!_.any(temp, function(a) { return a.source == link.source && a.target == link.target; })) {
       temp.push(link);
    }
});
Artūras
  • 453
  • 3
  • 12