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.

Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
Ross s
  • 49
  • 5

5 Answers5

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>
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
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)
Andy
  • 61,948
  • 13
  • 68
  • 95
0

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

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

console.log(filtered);
  • Why the downvote though, that's a totally valid answer. Have the decency to explain your actions when you do them ... –  Jun 19 '19 at 14:40
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);
Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62
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)
ellipsis
  • 12,049
  • 2
  • 17
  • 33
  • `isNaN(Number(e))` - converting using `Number` is redundant. `isNaN` is already enough. It's badly named - it's actually `isArgumentGoingToConvertToNaNWhenYouConvertItToNumber` – VLAZ Jun 19 '19 at 14:43