1

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.

2
  • 1
    iterate the array and check it dataType using typeof Commented Oct 4, 2014 at 7:10
  • I take it you meant "a", not a? Or is a a variable containing a string? Commented Oct 4, 2014 at 7:18

2 Answers 2

3

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"; 
});
Sign up to request clarification or add additional context in comments.

1 Comment

I'd to do .filter(isFinite). Number will filter out zeros.
3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.