[英]Filter an array in order to group items by data type
我懂了:
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
运算符与filter
方法结合使用,该方法接受回调函数作为参数。
filter()方法创建一个新数组,其中包含所有传递由提供的函数实现的测试的元素。
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));
var arr= ["three", "2", "five", "ten", "111", 1, 2, "forty", "33", 33];
var num=[];
var str=[];
for(i=0;i<arr.length;i++){
if(arr[i].includes('"') || arr[i].includes("'"))
str.push(arr[i]);
else
num.push(arr[i]);
}
您需要使用create一个函数来检查您给出的是字符串还是整数,并将值推送到右侧数组。
我没有测试下面的代码,但它应该是一个很好的起点。
var arr= ["three", "2", "five", "ten", "111", 1, 2, "forty", "33", 33];
var strArr = [];
var numArr = [];
var arrayLength = arr.length();
// iterates trough the array
for (i; i < arr.length(); i++)
{
//Check if the given value in the array is string
if (typeof arr[i] === 'string')
{
// adds the value you are checking to the strArr
strArr.push(arr[i]);
}
//Check if the given value in the array is integer
if (typeof arr[i] === 'number' && isFinite(value))
{
// adds the value you are checking to the numArr
numArr.push(arr[i]);
}
}
希望有所帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.