Javascript/jQuery: remove all non-numeric values from array
Solution 1:
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.
Solution 2:
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.
Solution 3:
Here is a ES6 version, although being similar to @Blazemonger solution, it's a bit shorter and uses regexp
which has the advantage of being predictable and does not lead to unexpected behaviours.
let arr = ["83", "helloworld", "0", "", false, 2131, 3.3, "3.3", 0];
const onlyNumbers = arr.filter(value => /^-?\d+\.?\d*$/.test(value));
console.log(onlyNumbers); //only numbers