【发布时间】:2018-08-16 14:20:56
【问题描述】:
我想对一组电话号码进行排序,并根据区号输出数组的长度。例如:
var nums = [
8881756223,
8881742341,
9187221757,
...,
]
还有比这更多的条目(大约 1300 个),并且已经按数字顺序排列。但是,我想要它做的是:
1. look at the first 3 numbers of the first entry
2. look at the next entries first 3 numbers
3. if they are different, then splice the array, console.log new array.length
and console.log that area code
例如,我提供的数组中的前两个数字将被拼接到他们的新数组中,控制台输出将是:
areacode: 888, length: 1
areacode: 918, length: 0
我知道搜索第一个数字的正则表达式,但我不完全知道如何将它们拼接到自己的数组中......就像我知道的那样,使用拼接,但是将两者与逻辑语句进行比较,我'在使用正则表达式时,我们从来没有做过类似的事情。
我目前的情况是这样的:
const patt = new RegExp('^\d{3}')
var newArr = nums.filter(x => patt)
for (var i = 0; i < newArr.length; i++)
console.log(newArr[i])
但这是吐出完整的号码,而不是区号本身。当然,在我得到它只是吐出区号之后,我会添加逻辑来排序。
【问题讨论】:
-
你能不能只提供 15-20 行数据,以便我测试我的解决方案
-
是的。 6143617235,6143928156,7401156789,7409012350,7402055551,7602791265,7602323866,7602567867,7602921268,8035982163,8031346664,8059136465,8501299919,8562190540,8568451921,8568672222,8562345783,9189281004,9193570918,9190678129,跨度>
-
@WiktorStribiżew 这似乎已经做到了。干得好,该死,我需要学习如何使用正则表达式..
标签: javascript arrays regex sorting