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;
Solution 1:
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]);
}
}
}
Solution 2:
Assuming I understand your question... maybe check to see if the value has already been visited by the outer loop?
var visited = {}
for(i in obj) {
visited[i] = true;
for(j in obj) {
if(j in visited){ continue; }
foo(obj[i], obj[j]);
}
}
Solution 3:
Use Object.keys() to get the list of keys out as an array:
keys = Object.keys();
for(i=0;i<keys.length;i++) {
for(j=i+1;j<keys.length;j++) {
foo(obj[keys[i]], obj[keys[j]]);
}
}
Solution 4:
Maybe You can try unset used objects:
for(i in obj) {
var a = obj[i];
delete obj[i];
for(j in obj) {
foo(a, obj[j]);
}
}
If you need to original obj in tact see: How do I correctly clone a JavaScript object?
Solution 5:
You can push the object keys into an array:
var obj_keys = [];
for (i in obj) {
obj_keys.push(i);
}
for(i = 0; i < obj_keys.length; ++i) {
for(j = i + 1; j < obj_keys.length; ++j) {
foo(obj[obj_keys[i]], obj[obj_keys[j]]);
}
}
Post a Comment for "How Can I Iterate Over All Unique Pairs Of Entries In An Object?"