如何在 javascript 中过滤数组?
2017-08-28
22111
这是一个数组:
total = ["10%", 1000, "5%", 2000]
我怎样才能将它们过滤成两个数组,如:
percentage = ["10%","5%"]
absolute = [1000,2000]
...使用 JavaScript 数组过滤器。
3个回答
您应该使用
filter
方法,该方法接受
callback
函数。
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
此外,使用
typeof
运算符
来找出数组中项目的类型。
typeof
运算符返回一个字符串,指示未评估操作数的类型。
let total = ["10%", "1000", "5%", "2000"];
let percentage = total.filter(function(item){
return typeof item == 'string' && item.includes('%');
});
console.log(percentage);
let absolute = total.filter(function(item){
return typeof item == 'number' || !isNaN(item);
});
console.log(absolute);
Mihai Alexandru-Ionut
2017-08-28
877825660
alexmac
2017-08-28
Make two arrays from one array by separating number and string using advance
js.
let total = ["10%", 1000, "5%", 2000];
var percentage = total.filter(e => isNaN(e));
var absolute = total.filter(e => !isNaN(e));
console.log({percentage , absolute});
Gowtham Kumar B V
2020-04-27