javascript - 过滤数组以便按数据类型对项目进行分组

标签 javascript arrays

我明白了:

var arr= ["three", "2", "five", "ten", "111", 1, 2, "forty", "33", 33];

我需要它是 2 个新数组 一个只有数字,另一个只有字符串

像这样:

var strArr = ["three", "2", "five", "ten", "111","forty", "33"];
var numArr = [1, 2, 33];

我应该怎么做?

最佳答案

您可以将 typeof operatorfilter 方法结合使用,该方法接受一个回调 函数作为参数。

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

var arr= ["three", "2", "five", "ten", "111", 1, 2, "forty", "33", 33];
var numbers = arr.filter(function(item){
  return typeof item == 'number';
});
var strings = arr.filter(function(item){
  return typeof item == 'string';
});
console.log(numbers);
console.log(strings);

您可以使用 arrow 函数来实现轻型解决方案。

['number', 'string'].map(i => arr.filter(a => typeof a == i));

关于javascript - 过滤数组以便按数据类型对项目进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48341390/

相关文章:

javascript - 闭包缓存变量?

javascript - javascript中concat的语法

javascript - Angular 模板 : ng-repeat comma-separated links

javascript - 在 JavaScript 中从数组中过滤 null

objective-c - Swift 中的 CoreData 到数组

javascript - html: 如何在多个选择标签中添加默认选项?

JavaScript 按字符数过滤 <input> 值的数组

c - 在函数之间传递结构数组

javascript - 如何取出双数组中的对象

arrays - 如何用仅允许 array.add(int) 的语言模拟 array.remove(int)