Ambili
Ambili

Reputation: 141

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?

Upvotes: 10

Views: 68509

Answers (12)

Bhavik Vagadia
Bhavik Vagadia

Reputation: 69

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.

Upvotes: 0

Rashid Qazizada
Rashid Qazizada

Reputation: 27

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);

Upvotes: 1

Sujith S
Sujith S

Reputation: 601

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

Upvotes: 3

20B2
20B2

Reputation: 2141

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)

Upvotes: 22

DevLoverUmar
DevLoverUmar

Reputation: 13933

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);

Upvotes: 0

Raggaeboys
Raggaeboys

Reputation: 15

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.

Upvotes: 0

Lajos Arpad
Lajos Arpad

Reputation: 76554

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.

Upvotes: 0

Govinda Rajbhar
Govinda Rajbhar

Reputation: 3034

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);

Upvotes: 2

Dinesh undefined
Dinesh undefined

Reputation: 5546

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);

Upvotes: 3

Le Hung
Le Hung

Reputation: 51

You usage func helper in filter

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

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386604

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);

Upvotes: 1

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

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);

Upvotes: 10

Related Questions