Agus Putra Dana
Agus Putra Dana

Reputation: 719

Remove string from array

I have an array that contain number and string, I want to remove all string from the array. Here is the array:

var numbOnly = [1, 3, "a", 7];

In this case, I want to remove a from numbOnly (result numbOnly = [1, 3, 7]).

Thanks.

Upvotes: 1

Views: 117

Answers (2)

Amit Joki
Amit Joki

Reputation: 59232

You can just use this:

var numbOnly = [1, 3, "a", 7];
var newArr = numbOnly.filter(isFinite)  // [1, 3, 7]

The above works really well if you don't have strings like "1" in the array. To overcome that, you can filter the array like this:

newArr = numbOnly.filter(function(x){
   return typeof x == "number"; 
});

Upvotes: 3

thefourtheye
thefourtheye

Reputation: 239473

You can use Array.prototype.filter function along with Object.prototype.toString like this

var array = [1, 3, 'a', 7];

var numbOnly = array.filter(function(currentItem) {
    return Object.prototype.toString.call(currentItem).indexOf('Number')!==-1;
});

console.log(numbOnly);
# [ 1, 3, 7 ]

Alternatively, you can use typeof to check the type like this

return typeof currentItem === 'number';

The filter function will retain the current element in the resulting list only if the function passed to it returns true for the current item. In this case, we are checking if the type of the current item is number or not. So, filter will keep only the items whose type is number, in the result.

Upvotes: 3

Related Questions