如何检测数组是否具有年份值并进行定义?

时间:2018-10-20 15:37:24

标签: javascript arrays node.js

这是示例数组:

[ 'test', '1994', 'test', 'test', '2018']

我需要的是示例数组中的2个数组:

[ 'test', 'test', 'test' ]

[ '1994', '2018' ]

我尝试使用indexOf,但是接缝无法传递具有所有可能年份值(〜1900-present / 2018)的数组

我想出了switch statment会起作用的地方,但是它将复制很多代码,我相信有更好的方法可以做到这一点。

编辑:

你们中的某些人不仅不知道我想获得的价值,还不理解我的价值,所以正则表达式的答案与我想要的最接近,我只是转到^(19|20)\d{2}$后,请替换正则表达式。因此年份可能只有1900年至2099年。

5 个答案:

答案 0 :(得分:4)

您可以检查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);

答案 1 :(得分:2)

您可以将阵列缩减为2个单独的阵列。检查字符串是否可以转换为介于1900-2018之间的数字,并且其结果为:

  1. false-强制转换为0,并推送到第一个子数组
  2. true-强制转换为1,并推送到第二个子数组

然后您可以使用数组解构获得两个数组。

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

答案 2 :(得分:2)

您可以使用函数COUNT(DISTINCT ..)根据字符串的内容对字符串进行分组。

col1
reduce

答案 3 :(得分:1)

您可以使用正则表达式执行此操作:

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

答案 4 :(得分:0)

您还可以结合使用filterisNaN支票来完成此操作。

var array = ['test', '1994', 'test', 'test', '2018'];

var text = array.filter(e => isNaN(e)),
    years = array.filter(e => !isNaN(e));
    
console.log(text);
console.log(years);