For an array: ["5","something","","83","text",""]
How to remove all non-numeric and empty values from an array? Desired output: ["5","83"]
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.
Here is a ES6 version which tests when values from an array match the regexp
let arr = ["83", "helloworld", "0", "", false, 2131, 3.3, "3.3", 0];
const onlyNumbers = arr.filter(value => /^-?\d+\.?\d*$/.test(value));
console.log(onlyNumbers);
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.
const arr = ["5","something","","83","text",""] const onlyNumbers = arr.filter((item) => typeof item === 'number')
this should work.
© 2022 - 2024 — McMap. All rights reserved.