Currently, I have an array data structure that I repeat like this, invoking foofor 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 realized that it is better to use an object instead of an array, since I can easily add and remove elements by name.
However, I do not 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 create a pair of identical elements. Is there an easy way to iterate over an object in the same way as I do in an array in my first code example?
Update:
Checking the performance of solutions on jsperf .
source
share