[英]How can I detect if array have year value and define it?
Here is example array: 这是示例数组:
[ 'test', '1994', 'test', 'test', '2018']
What I need is 2 arrays out of example array: 我需要的是示例数组中的2个数组:
[ 'test', 'test', 'test' ]
and 和
[ '1994', '2018' ]
I tried to use indexOf
but seams I can't pass array with all possiable years value (~1900-present/2018) 我尝试使用
indexOf
但接缝我无法传递具有所有可能年值的数组(~1900-present / 2018)
I figure out what switch statment
will work but it's gonna be a lot of copy pasted code, I believe there is better way to do it. 我知道什么样的
switch statment
可以工作但是它会有很多复制粘贴的代码,我相信有更好的方法可以做到这一点。
Edit: 编辑:
Some of you didn't understand what I wanted to get year value not just a number , so answer with regex is most closed to what I wanted, i just replace regex after googling to ^(19|20)\\d{2}$
. 你们有些人不明白我想得到的年份价值不仅仅是一个数字 ,所以使用正则表达式的答案最接近我想要的,我只是在谷歌搜索到
^(19|20)\\d{2}$
后替换正则表达式。 So year could be only 1900-2099. 所以那一年可能只有1900-2099。
You could take a check isNaN
and push the value to either number ot text array. 您可以检查
isNaN
并将值推送到任一数字文本数组。
var array = ['test', '1994', 'test', 'test', '2018'], text = [], numbers = []; array.forEach(s => [numbers, text][+/^(19|20)\\d{2}$/.test(s)].push(s)); console.log(text); console.log(numbers);
You can reduce the array to 2 separate arrays. 您可以将阵列减少到2个单独的阵列。 Check if the string can be casted to a number between the range of 1900-2018, and if it evaluates to:
检查字符串是否可以转换为1900-2018范围内的数字,如果它的计算结果为:
false
- casted to 0, and pushed to the 1st sub-array false
- 转换为0,并推送到第1个子数组 true
- casted to 1, and pushed to the 2nd sub-array true
- 转换为1,并推送到第二个子阵列 Then you can get the two arrays using array destructuring. 然后你可以使用数组解构获得两个数组。
const arr = ['test', '1994', 'test', 'test', '2018']; const isYear = (n) => n >= 1900 && n <= 2018; const [test, years] = arr.reduce((r, s) => { r[+isYear(+s)].push(s); return r; }, [[], []]); console.log(test); console.log(years);
You can use the function reduce
to group the strings according to their contents. 您可以使用函数
reduce
根据其内容对字符串进行分组。
let arr = [ 'test', '1994', 'test', 'test', '2018'], isYear = (s) => !isNaN(Number(s.trim())), result = arr.reduce((a, s) => { if (isYear(s)) a.years.push(s); else a.strings.push(s); return a; } , {years: [], strings: []}); console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can use regex to do this: 您可以使用正则表达式执行此操作:
var arr = [ 'test', '1994', 'test', 'test', '2018'];
var dates = [];
var nonDates = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i].match(/^\d{4}$/))
dates.push(arr[i]);
else
nonDates.push(arr[i]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.