Mohammad Ibrahim
Mohammad Ibrahim

Reputation: 56

Getting wrong result with Number.isInteger() method, javascript

I've been trying the Number.isInteger() method on chrome console. and after doing a for loop and checking the result with the console.log(arr); I'm getting an array with only one value of 1. like this [1];

 var arr = [1,2,3,'some','string'];

for (var i = 0; i < arr.length; i++) {
    if (Number.isInteger(arr[i])) {
        arr.splice(arr.indexOf(arr[i], 1));
    }
}

Any one have an idea, if I'm doing it wrong or something. thanks for help.

Upvotes: 1

Views: 444

Answers (3)

ibrahim mahrir
ibrahim mahrir

Reputation: 31712

You have a major problem, you are continually removing items from the array while looping through it. You have to go back one step (i--) every time an item is removed.

var arr = [1,2,3,'some','string'];

for (var i = 0; i < arr.length; i++) {
    if (!isNaN(arr[i])) { // isNaN return true if it's not a valid number, so we have to inverse the test
        arr.splice(i, 1); // if it's a valid number remove the element at the index i (no need to search for the index using indexOf, we already have it its i)
        i--;              // if we remove an element, we have to go back one step (or we will leave one item behind every time we remove another)
    }
}


console.log(arr);

Upvotes: 1

wlh
wlh

Reputation: 3525

The `.splice()' method makes changes to the array itself.

So for each iteration of the array, you are changing it fundamentally.

If you want the array to include only integers:

    var arr = [1,2,3,'some','string'];

    var newArray = [];

    arr.forEach(function(element) {
        if (Number.isInteger(element)){
            newArray.push(element);
        }
    });

    console.log(newArray);

Upvotes: 0

gianni
gianni

Reputation: 1357

You could use typeof instead:

var arr = [1,2,3,'some','string'];
for (var i = 0; i < arr.length; i++) {
  if (typeof arr[i] == 'number') {
    arr.splice(arr.indexOf(arr[i], 1));
  }
}

Upvotes: 0

Related Questions