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

后端 未结 2 1879
野趣味
野趣味 2020-12-21 06:43

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

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

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-21 07:08

    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.

提交回复
热议问题