I have an array of objects each of which has a left and right element. In some cases the within the array, the left may equal the right and visa versa for distinct objects within the array. These "duplicates" need to be removed.
So for example, I have an array of objects like this...
[
{"left":"cow","right":"pig"},
{"left":"horse","right":"pig"},
{"left":"rabbit","right":"pig"},
{"left":"bird","right":"pig"},
{"left":"bear","right":"pig"},
{"left":"cow","right":"bird"},
{"left":"horse","right":"bird"},
{"left":"pig","right":"bird"},
{"left":"cow","right":"horse"},
{"left":"bird","right":"horse"},
{"left":"pig","right":"horse"},
{"left":"rabbit","right":"horse"},
{"left":"horse","right":"cow"},
{"left":"pig","right":"cow"},
{"left":"bird","right":"cow"},
{"left":"bear","right":"cow"},
{"left":"horse","right":"rabbit"},
{"left":"pig","right":"rabbit"},
{"left":"bear","right":"rabbit"},
{"left":"pig","right":"bear"},
{"left":"rabbit","right":"bear"},
{"left":"cow","right":"bear"}
]
And I need to filter it down to the unique pairs, like this...
[
{"left":"cow","right":"pig"},
{"left":"horse","right":"pig"},
{"left":"rabbit","right":"pig"},
{"left":"bird","right":"pig"},
{"left":"bear","right":"pig"},
{"left":"cow","right":"bird"},
{"left":"horse","right":"bird"},
{"left":"cow","right":"horse"},
{"left":"rabbit","right":"horse"},
{"left":"bear","right":"cow"},
{"left":"bear","right":"rabbit"}
]
Using javascript.
You're going to need to use Array.prototype.filter, as well as a basic object to keep track of which pairs have been touched.
var input = [ ... ];
var pairs = {};
var output = input
.filter(function(item) {
if (pairs[item.left] == item.right ||
pairs[item.right] == item.left)
return false;
pairs[item.left] = item.right;
return true;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With