【问题标题】:Javascript array sorting using regex使用正则表达式的 Javascript 数组排序
【发布时间】: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


【解决方案1】:

我建议使用

nums.map(x => ("" + x).replace(/^(\d{3})[^]*/, '$1'))

这里,

  • "" + x 会将数字强制转换为字符串
  • .replace(/^(\d{3})[^]*/, '$1') 将删除保留前 3 位数字的所有字符(或不匹配时的整个字符串)。

JS 演示:

var nums = [
    8881756223,
    8881742341,
    9187221757,
    1
];
var res = nums.map(x => ("" + x).replace(/^(\d{3})[^]*/, '$1'));
console.log(res);

【讨论】:

    【解决方案2】:

    你可以试试这个

    var nums = [
        8881756223,
        8881742341,
        9187221757
    ]
    
    var prefixes = nums.map(x=>(x+"").substr(0,3));
    
    var votes =  prefixes.reduce(
    (votes, curr) => {
        if(votes[curr]) votes[curr]++;
        else {votes[curr] =1;}
        return votes;
    }, {});
    
    var ans = Object.keys(votes).map(x => ({areacode:x, length:votes[x]}));
    
    console.log(ans);
    

    ans 将保存您需要的值

    这里解释了我使用的计票技术https://igghub.github.io/2017/01/15/useful-js-reduce-trick/

    【讨论】:

      猜你喜欢
      • 2015-10-22
      • 2014-11-20
      • 2013-12-09
      • 2012-11-23
      • 2020-02-03
      • 1970-01-01
      • 2019-10-18
      • 1970-01-01
      • 2021-08-19
      相关资源
      最近更新 更多