10

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?

9
  • 2
    you have strings, not numbers in the array. Commented Jun 19, 2017 at 11:08
  • 5
    digit? you serious? What's res? Commented Jun 19, 2017 at 11:09
  • 2
    Did you even check on internet how to check if a string is a number ? Commented Jun 19, 2017 at 11:10
  • I would ask that you learn what the basic types of JavaScript are. Commented Jun 19, 2017 at 11:10
  • 1
    Possible duplicate of Check if string contains only digits Commented Jun 19, 2017 at 11:14

12 Answers 12

22

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)
Sign up to request clarification or add additional context in comments.

4 Comments

I was just about to write the same. this should be the top answer.
This will exclude "0" because 0 is a falsy value
filter(Number) will except zeros, you should use filter(Number.isInteger)
@аlexdykyі filter(Number.isInteger) will exclude all the integer values like "1", "3",etc in array as well.
10

Making a small change to your code to make it work, this might possibly work.

var str = ["https://xx.jpg", "https://xx.jpg", "1", "https://guide.jpg", "2", "/static.jpg"];
var filtered = str.filter(function (item) {
  return !(parseInt(item) == item);
});
console.log(filtered);

Or if you want the numbers:

var str = ["https://xx.jpg", "https://xx.jpg", "1", "https://guide.jpg", "2", "/static.jpg"];
var filtered = str.filter(function (item) {
  return (parseInt(item) == item);
});
console.log(filtered);

5 Comments

The question asks us to filter out numbers, so 1.5 should be filtered out as well.
You are right, parseInt(1.5) returns 1, I thought it returns NaN. My bad
I really don't understand why people would like to downvote!
I think you should not care. I upvoted your answer when I was convinced it is correct. My answer was not upvoted, nor downvoted. I am regularly downvoted as well when I am convinced I have given a correct answer, but this will not stop me from helping.
@LajosArpad Agreed. Just curious to know why.
3

Use isNaN().

var str=["https://xx.jpg","https://xx.jpg","1","https://guide.jpg","2","/static.jpg"];

var filtered = str.filter(function(item) {
     
     return (!isNaN(item)); 
     });
     
console.log(filtered);

1 Comment

"1" and "2" should be filtered out instead of the other items, you need isNaN instead of !isNaN. Also, your answer does not address the case of "" or null.
3
var str = ["https://xx.jpg","https://xx.jpg","1","https://guide.jpg","2", "/static.jpg" ]
str.filter(item=>!isNaN(parseInt(item)))

parseInt convert number to integer and other values converted to "NaN", isNaN function validate value is either "NaN" or not

https://www.w3schools.com/jsref/jsref_isnan.asp https://www.w3schools.com/jsref/jsref_parseint.asp

1 Comment

this answer worked for me!
2

If you want to check if a string only contains numeric digits, you can use regular expressions.

var str = ["https://xx.jpg", "https://xx.jpg", "1", "https://guide.jpg", "2", "/static.jpg"];
var filtered = str.filter(function (item) {
  return item.match(/^-?\d+$/);
});
console.log(filtered);

Comments

1

You could use a regular expression which test a string, if it contains only digits.

var array = ["https://xx.jpg", "https://xx.jpg", "1", "https://guide.jpg", "2", "/static.jpg"];

array = array.filter(function (a) {
    return !/^\d+$/.test(a);
});

console.log(array);

Comments

1
const intArray = [];
const strArray = [];
const rest_test_parameters = (...args) => {

  args.filter((item) => {
    if (parseInt(item)) {
      return intArray.push(parseInt(item));
    }
    strArray.push(item);
  });
};
const objects = {
  a: "a",
  b: "c"
};
rest_test_parameters(1, 2, "99","hello", objects);
console.log("intArray", intArray);
console.log("strArray",strArray);

Comments

0

You usage func helper in filter

 function isNumber(n) {  return !isNaN(parseFloat(n)) && isFinite(n);}

Comments

0
str = str.filter(function(item) {
    return (item !== 0) && ((!item) || (isNaN(item)));
});

The right side of the operation calls filter and passes a function which returns true if an item is not 0 and it is either falsey or not a number; otherwise it returns false. For instance "" or null should be kept in the array as far as the specification goes. With this approach we get the desired array and we assign it to the str variable.

Comments

0

const filterNumbers = [123456789, 'limit', 'elite', 987654321, 'destruction', 'present'];

const result = filterNumbers.filter(number => parseInt(number) == number);

console.log(result);

Here's similar code that returns the number instead of the string. The => is just alternative syntax for function and return (see arrow function expressions), but will yield the same result.

Comments

0

Most of the above answers are good, but missing one thing; filtering out array of numbers(neither integer, nor string form of numbers).

I haved added the snippet to address those little issues.

var str = ["https://xx.jpg", "https://xx.jpg", "1", "https://guide.jpg", "2.4", "/static.jpg","4"];
var filteredNumbers = str.filter(item=> parseFloat(item) == item).map(item=>parseFloat(item));
console.log(filteredNumbers);

Comments

0

Here's a one liner: arr.filter(n => (parseInt(n)===0 || +n)).map(Number)

This is assuming it is a flat array and not a nested one.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.