这是一个数组,
total = ["10%", 1000, "5%", 2000]
. 我如何将它们过滤成两个数组,例如百分比 = ["10%","5%"] 和绝对值 = [1000,2000] 使用 javascript 数组过滤器。
这是一个数组,
total = ["10%", 1000, "5%", 2000]
. 我如何将它们过滤成两个数组,例如百分比 = ["10%","5%"] 和绝对值 = [1000,2000] 使用 javascript 数组过滤器。
您应该使用filter
接受callback
函数的方法。
filter() 方法创建一个新数组,其中包含通过提供的函数实现的测试的所有元素。
另外,使用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);
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);
您可以使用正则表达式,因为您的数组中只有字符串。
为了 % :
total.filter(function(element){
return /^[0-9]+\%$/gi.test(element);
});
对于绝对:
total.filter(function(element){
return /^[0-9]+$/gi.test(element);
});
您可以使用 Array#reduce 来拆分数组:
const total = ["10%", 1000, "5%", 2000];
const { absolute, percentage } = total.reduce((arrs, item) => {
const key = typeof item === 'number' ? 'absolute' : 'percentage';
arrs[key].push(item);
return arrs;
}, { percentage: [], absolute: [] });
console.log(absolute);
console.log(percentage);
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});