Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter unique pairs from JSON using Javascript

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.

like image 606
dacracot Avatar asked Sep 27 '22 10:09

dacracot


1 Answers

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;
    });
like image 110
TbWill4321 Avatar answered Sep 28 '22 23:09

TbWill4321