Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering numbers out from an array

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?

like image 766
Ambili Avatar asked Jun 19 '17 11:06

Ambili


1 Answers

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)
like image 88
20B2 Avatar answered Nov 07 '22 07:11

20B2