简体   繁体   中英

Javascript/jQuery: remove all non-numeric values from array

For an array: ["5","something","","83","text",""]

How to remove all non-numeric and empty values from an array? Desired output: ["5","83"]

Use array.filter() and a callback function that checks if a value is numeric :

var arr2 = arr.filter(function(el) {
    return el.length && el==+el;
//  more comprehensive: return !isNaN(parseFloat(el)) && isFinite(el);
});

array.filter has a polyfill for older browsers like IE8.

I needed to do this, and following a bunny trail based on the answer above, I found out that this functionality has now been built in to jQuery itself in the form of $.isNumeric() :

    $('#button').click(function(){
      // create an array out of the input, and optional second array.
      var testArray = $('input[name=numbers]').val().split(",");
      var rejectArray = [];

      // push non numeric numbers into a reject array (optional)
      testArray.forEach(function(val){
        if (!$.isNumeric(val)) rejectArray.push(val)
      });

      // Number() is a native function that takes strings and 
      // converts them into numeric values, or NaN if it fails.
      testArray = testArray.map(Number);

      /*focus on this line:*/
      testArray1 = testArray.filter(function(val){
        // following line will return false if it sees NaN.
        return $.isNumeric(val)
      });
    });

So, you essentially .filter() , and the function you give .filter() is $.isNumeric() , which gives a true/false value depending on whether that item is numeric or not. Good resources are available and easily found via google on how these are used. My code actually pushes the reject code out into another array to notify the user they gave bad input up above, so you have an example of both directions of functionality.

Here is an ES6 version, although being similar to @Blazemonger solution, it's a bit more simplified:

 let arr = ["5","something","","83","text",""]; const onlyNumbers = arr.filter(v => +v); console.log(onlyNumbers);

Here, I am relying on the unary plus operand which converts a string into a number. Althought sometimes it might lead to some unexpected behaviour (for example true is not filtered), it works just fine with your array since it contains only strings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM