简体   繁体   English

从数组中过滤出数字

[英]Filtering numbers out from an array

I have an array like below and need to filter out the numbers from it ex: [1,2]我有一个如下所示的数组,需要从中过滤掉数字: [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"].在您的情况下,结果数组将为 ["1", "2"]。

If the original array contains 0 or "0", then they will not be present in the resulting array.如果原始数组包含 0 或“0”,则它们将不会出现在结果数组中。

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.这将排除字符串形式的数字,如“1”、“2”等。

For both integer and float numbers,对于整数和浮点数,

str.filter(Number.isFinite)

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

Use isNaN() .使用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);

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

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

您在过滤器中使用 func 助手

 function isNumber(n) {  return !isNaN(parseFloat(n)) && isFinite(n);}
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;操作的右侧调用filter并传递一个function ,如果项目不是 0 并且它是假的或不是数字,则该function返回true otherwise it returns false .否则返回false For instance "" or null should be kept in the array as far as the specification goes.例如,就规范而言, ""null应保留在数组中。 With this approach we get the desired array and we assign it to the str variable.通过这种方法,我们获得了所需的数组,并将其分配给str变量。

 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. =>只是functionreturn替代语法(参见箭头函数表达式),但会产生相同的结果。

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

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 parseInt 将数字转换为整数,其他值转换为“NaN”,isNaN 函数验证值是否为“NaN”

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

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

Here's a one liner: arr.filter(n => (parseInt(n)===0 || +n)).map(Number)这是一个衬里: arr.filter(n => (parseInt(n)===0 || +n)).map(Number)

This is assuming it is a flat array and not a nested one.这是假设它是一个平面数组而不是嵌套数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM