Search code examples
javascriptarraysfilternumbersunderscore.js

Need to remove string from an Array


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.


Solution

  • 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>