I recently found out that two identical arrays are inherently non-equal and will never return 'true' when compared. My challenge was to solve the following problem:
Write a function called moveAllZeros. It will take as its input an array of numbers. Move all 0's in that array to the end of it while maintaining the relative order of the non-zero elements. You must mutate the array. You cannot make a copy.
And I did so using the following code:
const moveAllZeros = function (arr) {
let i = 0;
let zeroCounter = 0;
while (i+zeroCounter < arr.length) {
if ( arr[i] === 0 ) {
arr.splice(i, 1);
arr.push(0);
zeroCounter ++;
} else {
i++;
}
}
return arr;
};
const testArr = [1, 0, 3, 0, 0, 4, 9, 22, 18, 100, 20];
const resultArr = [1, 3, 4, 9, 22, 18, 100, 20, 0, 0, 0];
console.log(moveAllZeros(testArr));
I had assumed that I would be able to simply compare my output to the known value of the solution array, but this isn't true. It took me a good long time trying to figure this out using both ==
and ===
but to no avail until a coworker reminded me that in JavaScript, no array will never be equal to another array unless they are THE SAME ARRAY.
This is because, in JavaScript, all object types (including array) are compared by reference, not value. Per reddit user /u/mursfZOR's comment on this thread, "only the primitive values can be compared for equality - i.e. boolean, string, number. The special values null and undefined also act this way."
Lesson learned.
Top comments (0)