I have an array var data=["test","10%","abc","20%"];
Now is there any way so that i can filter out and get only the numbers something like result=["10%","20%"];
You can use this function:
Explanation: We create a new array and push
all the elements of the old array,
if the first letter
can be converted into a digit.
var data = ["test", "10%", "abc", "20%"];
function onlyNumbers(array) {
var newArr = [];
array.forEach(function(e) {
if (parseInt(e.charAt(0))) {
newArr.push(e);
}
})
return newArr;
}
var dataNew = onlyNumbers(data); // <-- ["10%","20%"]
document.write(JSON.stringify(dataNew));
This will work out your problem and create new array with only good elements:
function check_percentage(num){
var regex = /^(\d+%)$/;
if (num.match(regex)){
return true;
}
}
var result=["babab","fg210%","120%","babab","4214210%","20%"],
filtered_result=[];
result.forEach(function(k,v){
if (check_percentage(k)){
filtered_result.push(k);
}
});
console.log(filtered_result);
You can use an underscore library and do:
var data=["test","10%","abc","20%"];
var result = _.filter(data, function(item) {
return item.match(/^(\d+|\d+[.]\d+)%?$/);
});
document.write(JSON.stringify(result));
<script src="http://underscorejs.org/underscore-min.js"></script>
And you can do the same without external library:
var data=["test","10%","abc","20%"],
result = [];
for(var i = 0; i < data.length; i++) {
if (data[i].match(/^(\d+|\d+[.]\d+)%?$/)) {
result.push(data[i]);
}
}
document.write(JSON.stringify(result));
RegExp object has exec method, which does the same.
%symbol? Have you tried writing a regular expression for that and using it with Array#filter?data.filter(parseInt);fails ?Array#filterpasses three arguments, the second of which is the index of the element being tested and which will be interpreted byparseIntas a radix. As for the approach of usingparseIntin general: I never said it was wrong. It’s hard to know what’s right. Usingif (parseInt(e))will fail if you didn’t want negative numbers, or if you did want zero, or if you didn’t want strings like0xf, or if you didn’t want strings like7#?zQl, or if you wanted0.5%.