I have an array like below and need to filter out the numbers from it ex: [1,2]
var str = [
"https://xx.jpg",
"https://xx.jpg",
"1",
"https://guide.jpg",
"2",
"/static.jpg"
]
I have the below code :
var filtered = str.filter(function(item) {
return (typeof item === "number")
});
but it is not filtering as it is a string.
How to do it?
I think this is the most precise way to filter out numbers from an array.
str.filter(Number);
If the array contains a number in the form of string, then the resulting array will have the number in the form of string. In your case, the resulting array will be ["1", "2"].
If the original array contains 0 or "0", then they will not be present in the resulting array.
If resulting array should include only integer numbers,
str.filter(Number.isInteger)
This will exclude the number in the form of string like "1", "2", etc.
For both integer and float numbers,
str.filter(Number.isFinite)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With