ddjk
ddjk

Reputation: 133

JS: boolean values getting skipped in algorithm

I am doing an algo question that has me iterate through an array, remove all the 0's and place them at the end while preserving the order of the other elements. I came up with:

var moveZeros = function (arr) {
  let zeroArr = [];

  for (var x = arr.length - 1; x >= 0; x--) {
    if (arr[x] == 0) {
       zeroArr.push(0);
       arr.splice(x,1);
    }

}

  return arr.concat(zeroArr);
}

I've passed all cases but failed 2 test cases in which false is in the array.

returned: [1,4,2,"5",4,false,false,0,0,0]
expected: [1,4,2,"5",4,,0,0,0]

Upvotes: 0

Views: 39

Answers (2)

Edival
Edival

Reputation: 420

This is a behaviour of the equality operator (==) in javascript.

If one of the operands is Boolean, convert the Boolean operand to 1 if it is true and +0 if it is false.

There are more different behaviours when dealing with equality operator, but this is a good start:

The equality operator (==) checks whether its two operands are equal, returning a Boolean result. Unlike the strict equality operator, it attempts to convert and compare operands that are of different types.

You can find all the details (including the difference with strict operator === ) here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality

Upvotes: 0

Robert Mennell
Robert Mennell

Reputation: 2052

You're loosely comparing to 0. You need to exactly compare to it using === instead of ==.

var moveZeros = function (arr) {
  let zeroArr = [];

  for (var x = arr.length - 1; x >= 0; x--) {
    if (arr[x] === 0) {
       zeroArr.push(0);
       arr.splice(x,1);
    }

}

  return arr.concat(zeroArr);
}

For a value that can be falsy or truthy, if you want to compare directly to it you should use an exactly equals, not a loosely equals.

Upvotes: 2

Related Questions