这是一个数组:
total = ["10%", 1000, "5%", 2000]如何将这些数据过滤为两个数组,如:
percentage = ["10%","5%"]
absolute = [1000,2000]...using JavaScript阵列滤波器
发布于 2017-08-28 09:50:02
您应该使用filter方法,它接受一个callback函数。
filter()方法创建一个新数组,其中包含所有通过所提供函数实现的测试的元素。
另外,使用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);
发布于 2017-08-28 09:52:14
let total = ["10%", 1000, "5%", 2000];
let percents = total.filter(item => item.toString().includes('%'));
let numbers = total.filter(item => !item.toString().includes('%'));
console.log(percents, numbers);
发布于 2020-04-27 17:19:41
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});
https://stackoverflow.com/questions/45916135
复制相似问题