Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"]

like image 509
Steve Avatar asked Sep 05 '26 22:09

Steve


1 Answers

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.

like image 68
Blazemonger Avatar answered Sep 07 '26 11:09

Blazemonger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!