如何从文本文件中对多个数字(城市群体)进行分组?

时间:2018-04-24 14:09:05

标签: javascript

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

该项目代表针对分组人群的报告。老实说,我不知道如何解决这个问题,并希望得到任何帮助。如果我提出的问题没有意义,我可以尝试澄清。

以下是文本文件中需要分组的人口:

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

1 个答案:

答案 0 :(得分:0)

首先需要将文本文件与换行符(\n)分开。然后,您可以在该数组上map并使用正则表达式匹配名称和填充,并返回一个有用的对象。

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

然后,您可以对返回的对象数组进行过滤,并返回与条件匹配的记录子集。

const gt5000lt7500 = result.filter(city => city.population > 5000 && city.population < 7500);

Here's a demo