0
how to filter float values in the mixed array.
2 Respuestas
+ 1
function isFloat(n){
return (
typeof n === 'number' &&
!Number.isInteger(n) &&
!isNaN(n) &&
Number.isFinite(n)
);
}
const arr = [NaN,Infinity,{},[5,7],"test",5,5.0,1.5,4.7,true,1e4,8.127];
arr.filter(isFloat)
.forEach(e=>console.log(e));
+ 1
let arr = [6, 5.4, 3.01, 3]
// arr.filter() to filter the array
// return true if you wanna include it in the array, otherwise return false
// check first that is it a number or not,
// typeof 5 === "number" // true
// then check that if it is a float by comparing it with the integer version of it (rounded version) if it is same means it is not a float,
arr = arr.filter(num => {
if(typeof num === "number" && parseInt(num) !== num){
return true
} return false
})
console.log(arr);
// [ 5.4, 3.01 ]