如何在javascript中过滤数组?

IT技术 javascript arrays filter
2021-02-10 13:10:40

这是一个数组,

total = ["10%", 1000, "5%", 2000]. 我如何将它们过滤成两个数组,例如百分比 = ["10%","5%"] 和绝对值 = [1000,2000] 使用 javascript 数组过滤器。

6个回答

您应该使用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);

你得到了相反的过滤条件否定。
2021-03-15 13:10:40
百分比是具有 '%' 字符的那个,你否定了百分比而不是数字的返回值。
2021-03-17 13:10:40
@vkgade 你是什么意思?
2021-03-24 13:10:40

您可以使用正则表达式,因为您的数组中只有字符串。

为了 % :

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