需要从数组中删除字符串

时间:2019-06-19 14:25:32

标签: javascript arrays filter numbers underscore.js

我在这样的for循环中有一个数组:

var arr = ["abc", "5", "city", "2", "area", "2", "max", "choice"];

我只需要这样的数字:

var arr = ["5","2","2"];

所以有人可以帮忙吗?

5 个答案:

答案 0 :(得分:3)

另一种方法是将转换后的数字转换为字符串并与原始值进行比较。

var array = ["abc", "5", "city", "2", "area", "2", "max", "choice"],
    result = array.filter(v => (+v).toString() === v);

console.log(result);

使用isFinite

的方法更短

var array = ["abc", "5", "city", "2", "area", "2", "max", "choice"],
    result = array.filter(isFinite);

console.log(result);

虽然标有,但您可以使用下划线进行过滤和回调。

var array = ["abc", "5", "city", "2", "area", "2", "max", "choice"],
    result = _.filter(array, _.isFinite);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>

答案 1 :(得分:1)

filter将强制转换为整数的字符串替换为一个字符串:

var arr = ["abc", "5", "city", "2", "", "area", "2", "max", "choice"];

const out = arr.filter(el => (
  el !== '' && Number.isInteger(Number(el)))
);

console.log(out)

答案 2 :(得分:0)

var arr = ["abc", "5", "city", "2", "area", "2", "max", "choice"];

const filtered = arr.filter(item => !isNaN(item));

console.log(filtered);

答案 3 :(得分:0)

您可以将filter方法与isNaN函数var numbers = arr.filter(c=> !isNaN(c));

一起使用

var arr = ["abc", "5", "city", "2", "area", "2", "max", "choice"];
var numbers = arr.filter(c=> !isNaN(c));
console.log(numbers);

答案 4 :(得分:0)

使用forEach循环并使用isNaN()

检查

var arr = ["abc", "5", "city", "2", "area", "2", "max"];
var a=[];
arr.forEach(e=>isNaN(e)?true:a.push(e))
console.log(a)