首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何对文本文件中的多个数字(城市人口)进行分组?

如何对文本文件中的多个数字(城市人口)进行分组?
EN

Stack Overflow用户
提问于 2018-04-24 22:09:05
回答 1查看 38关注 0票数 0

我需要在JavaScript中获得包含以下内容的输出: population < 5000 > 7499,< 7500 > 9999,< 10000,并将空白population记录为NA。

此项目表示分组群体的报告。老实说,我不知道如何去做这件事,并感谢任何帮助。如果我问的问题没有意义,我可以试着澄清。

以下是文本文件中需要分组的群体:

代码语言:javascript
复制
Philadelphia city   1,526,006

Pittsburgh city 305,704

Harrisburg city 49,528

Altoona city    46,320

State College borough   42,034

Monroeville municipality    

Johnstown city  20,978

Murrysville municipality    20,079

McKeesport city 

Greensburg city 14,892

Indiana borough 13,975

Washington city 13,663

Meadville city  

New Kensington city 13,116

St. Marys city  13,070

Lower Burrell city  11,761

Munhall borough 

Jefferson Hills borough 10,619

Waynesboro borough  10,568

Oil City city   10,557

Uniontown city  10,372

Lock Haven city 9,772

Jeannette city  9,654

Beaver Falls city   

Swissvale borough   8,983

Mechanicsburg borough   8,981

Carbondale city 

Latrobe city    8,338

Grove City borough  8,322

Pleasant Hills borough  8,268

White Oak borough   

DuBois city 7,794

Monessen city   7,720

Connellsville city  7,637

Gettysburg borough  7,620

California borough  6,795

Somerset borough    6,277

Clearfield borough  

McKees Rocks borough    6,104

Punxsutawney borough    5,962

Duquesne city   5,565

Shippensburg borough    5,492

Fox Chapel borough  5,388

Turtle Creek borough    5,349

Clarion borough 5,276

Vandergrift borough 

Westmont borough    5,181

Arnold city 

Kutztown borough    5,012
EN

回答 1

Stack Overflow用户

发布于 2018-04-24 22:37:19

首先需要按换行符(\n)拆分文本文件。然后,您可以对该数组执行map操作,并使用正则表达式来匹配名称和种群,并返回一个有用的对象。

代码语言:javascript
复制
const result = file.split('\n').map(el => {
  const [whole, name, number] = el.match(/^([a-zA-Z\. ]+) ?([0-9,]*)$/);
  const population = +number.replace(',', '')
  return { name, population };
});

然后,您可以对返回的对象数组进行筛选,并返回符合条件的记录的子集。

代码语言:javascript
复制
const gt5000lt7500 = result.filter(city => city.population > 5000 && city.population < 7500);

Here's a demo

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50003818

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档