Given the following code to find Pythagorean Triples, why am I getting duplicates rather than excluding them with the While loop followed by the If condition?
var a, b, c, i, pyTrips, temp;
pyTrips = new Array();
temp = new Array();
for (a = 1; a <= 10; a++) {
for (b = 1; b <= 10; b++) {
with (Math) {
c = sqrt(pow(a, 2) + pow(b, 2));
}
if (c % 1 == 0) {
temp = a < b ? [a, b, c] : [b, a, c];
i = 0;
while (i < pyTrips.length && pyTrips[i] !== temp) {
i++;
}
if (i === pyTrips.length) {
pyTrips.push(temp);
}
console.log(pyTrips.toString());
}
}
}
I assume it’s the pyTrips[i]!==temp
part that’s tripping things up, but I’ve checked and there’s no type casting or anything; the comparison is in fact between two arrays. So not sure why the While loop seems to make it to pyTrips.length
every time.
3
Answers
Javascript arrays are objects. Objects are compared by comparing their object references, NOT by comparing their contents.
You can do this by using
toString
on both arrays:Your assumption is correct, you cannot compare two arrays directly. When you compare two arrays using the === operator, it compares their references, not their content.
One hacky way to solve this is to use
toString()
, convert the two arrays to string and then compareAnother way is to use a utility function which compares arrays
And then use it like
You can try clearing the array after each successful iteration: