Reputation: 1411
I am trying to make a function that takes an array and creates a pair of arrays
for example an array [1,2,3,4]
the pair will be:
pair = [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]] ;
And the pairs would be:
pairs = [[[1,2],[1,3]], [[1,2],[1,4]], [[1,2],[2,3]] .... [[2,4],[3,4] ] ;
So far my function looks like this:
function makePairs(arr) {
var l = arr.length -1 ,
pair = [];
for(var i=0; i < l ; i++ ) {
for(var j=i+1; j <= l ; j++ ) {
pair.push( [arr[i],arr[j]]) ;
}
}
// i get the desired pair by the above nested for loop...
// console.log(pair) ;
// i try to do the same nested for loop with the pair array..
// but i get [circular object Array];
var k = pair.length -1,
pairs = [] ;
for(var m=0; m < k ; m++ ) {
for(var n=m+1; n <= k ; n++ ) {
pairs.push( [pair[m],pair[n]]) ;
}
}
return pairs;
}
console.log( makePairs([1,2,3,4]) );
So the pair
gives me the desired pair but when I do the same type of nested
for
loop with the pair
array, I get [circular object Array]
. I thought
the nested for loop will work on the pairs
too but it does not.
I read that circular reference is formed between a javascript object and a native object causing memory leak but I don't know if that's happening here. please help.
Upvotes: 3
Views: 5902
Reputation: 7277
Try with JSON.stringify() and JSON.parse() like below:
console.log(
makePairs(
JSON.parse(
JSON.stringify([1,2,3,4])
)
)
);
Upvotes: 0
Reputation: 15397
I wonder if the issue is the debugger itself. It's outputting [circular object Array] any time it's referring to an item already referred to.
Try making a lot more console messages. Replace your last line with:
var answer = makePairs([1,2,3,4]);
for (var i = 0; i < answer.length; ++i) {
console.log("[[" + answer[i][0][0] + ", " + answer[i][0][1] + "], [" +
answer[i][1][0] + ", " + answer[i][1][1] + "]]");
}
I bet it will print out ok.
Upvotes: 1
Reputation: 17906
maybe you can make use of
console.dir( makePairs([1,2,3,4]) )
on chrome-console and latesst ff-firebug
Upvotes: 0