Need to remove string from an Array

Viewed 66

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.

5 Answers

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>

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)

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

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

console.log(filtered);

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);

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)

Related