简体   繁体   English

使用正则表达式的Javascript数组排序

[英]Javascript array sorting using regex

I want to sort an array of phone numbers and have the length of the array outputted based on areacode.我想对电话号码数组进行排序,并根据区号输出数组的长度。 For example:例如:

var nums = [
    8881756223,
    8881742341,
    9187221757,
    ...,
]

there are a lot more entries than that (roughly 1300) and its already in numerical order.有比这更多的条目(大约 1300 个),并且已经按数字顺序排列。 However, what I want it to do is:但是,我想要它做的是:

  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

so for example, the first two numbers in the array i provided will be spliced into their new array, and the console output will be:例如,我提供的数组中的前两个数字将拼接到它们的新数组中,控制台输出将是:

areacode: 888, length: 1
areacode: 918, length: 0

I know the regex to search for the first the numbers, but I don't exactly know how to splice them into their own arrays...Like i know, use splice, but comparing the two with logic statements, I've never had to do something like that before while using a regular expression.我知道搜索第一个数字的正则表达式,但我不完全知道如何将它们拼接到自己的数组中......就像我知道的那样,使用拼接,但是将两者与逻辑语句进行比较,我从来没有在使用正则表达式之前做类似的事情。

what I have so far is this:我到目前为止是这样的:

const patt = new RegExp('^\d{3}')

var newArr = nums.filter(x => patt)

for (var i = 0; i < newArr.length; i++)
    console.log(newArr[i])

but this is spitting out the full number, not the area code its self.但这是吐出完整号码,而不是区号本身。 Of course ill be adding the logic to sort after i get it to just spit out area codes.当然,在我得到它只是吐出区号之后,我会添加逻辑来进行排序。

you can try this你可以试试这个

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 will hold the value you require ans将保存您需要的值

vote counting technique i used is explained here https://igghub.github.io/2017/01/15/useful-js-reduce-trick/我使用的投票计数技术在这里解释https://igghub.github.io/2017/01/15/useful-js-reduce-trick/

I suggest using我建议使用

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

Here,这里,

  • "" + x will coerce the number to string "" + x将数字强制为字符串
  • .replace(/^(\\d{3})[^]*/, '$1') will remove all chars keeping the first 3 digits (or the whole string upon no match). .replace(/^(\\d{3})[^]*/, '$1')将删除保留前 3 位数字(或不匹配时的整个字符串.replace(/^(\\d{3})[^]*/, '$1')所有字符。

JS Demo: JS演示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM