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?
Performance testing the solutions on jsperf.
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]);
}
}
}
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