Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I iterate over all unique pairs of entries in an object?

I currently have an array data structure that I iterate over like this, calling foo on each unique pair of elements.

for(var i = 0; i < arr.length; i++) {
    for(var j = i + 1; j < arr.length; j++) {
        foo(arr[i], arr[j]);
    }
}

However, I've realized that I'd rather use an object instead of an array, since I can then add and remove elements by name very easily.

However, I can't see an obvious way to iterate over such an object. The closest I can get is:

for(i in obj) {
    for(j in obj) {
        foo(obj[i], obj[j]);
    }
}

Obviously, this will do each pair twice, and even produce a pair of identical elements. Is there an easy way to iterate over an object in the same way as I do in the array in my first code sample?

Update:

Performance testing the solutions on jsperf.

like image 904
Eric Avatar asked Dec 16 '22 00:12

Eric


1 Answers

My solution that was at first written as a comment:

Add an if (i < j) condition in the inner loop. It might not be the best solution, but it would work as long as the foo function does the same thing for foo(2, 10) and foo(10, 2):

for(i in obj) {
    for(j in obj) {
        if (i < j) {
            foo(obj[i], obj[j]);
        }
    }
}
like image 116
Simon Forsberg Avatar answered Dec 28 '22 12:12

Simon Forsberg