2

I have an array inside a for loop like this:

var arr = ["abc", "5", "city", "2", "area", "2", "max", "choice"];

And I need only number like this:

var arr = ["5","2","2"];

So can someone please help here.

1
  • Those "5", "2", and "2" are still strings Commented Jun 19, 2019 at 14:27

5 Answers 5

3

Another approach by using a converted number to a string and compare with the original value.

var array = ["abc", "5", "city", "2", "area", "2", "max", "choice"],
    result = array.filter(v => (+v).toString() === v);

console.log(result);

Just shorter approach with isFinite

var array = ["abc", "5", "city", "2", "area", "2", "max", "choice"],
    result = array.filter(isFinite);

console.log(result);

While tagged with , you could use the filtering and callback from underscore.

var array = ["abc", "5", "city", "2", "area", "2", "max", "choice"],
    result = _.filter(array, _.isFinite);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>

Sign up to request clarification or add additional context in comments.

3 Comments

If there are any trailing zeros in decimal like "2.10" this won't work
isFinite() is a great way to do this
I wasn't aware of isFinite coercing before determining numbers. Very useful! +1
1

filter out the strings that are integers when they're coerced to one:

var arr = ["abc", "5", "city", "2", "", "area", "2", "max", "choice"];

const out = arr.filter(el => (
  el !== '' && Number.isInteger(Number(el)))
);

console.log(out)

2 Comments

Number.isInteger(+"") returns true too.
Nice catch. Fixed.
0

var arr = ["abc", "5", "city", "2", "area", "2", "max", "choice"];

const filtered = arr.filter(item => !isNaN(item));

console.log(filtered);

1 Comment

Why the downvote though, that's a totally valid answer. Have the decency to explain your actions when you do them ...
0

You can use filter method with isNaN function var numbers = arr.filter(c=> !isNaN(c));

var arr = ["abc", "5", "city", "2", "area", "2", "max", "choice"];
var numbers = arr.filter(c=> !isNaN(c));
console.log(numbers);

Comments

0

Using forEach loops and checking using isNaN()

var arr = ["abc", "5", "city", "2", "area", "2", "max"];
var a=[];
arr.forEach(e=>isNaN(e)?true:a.push(e))
console.log(a)

1 Comment

isNaN(Number(e)) - converting using Number is redundant. isNaN is already enough. It's badly named - it's actually isArgumentGoingToConvertToNaNWhenYouConvertItToNumber

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.