admin管理员组

文章数量:814956

根据条件从数组中多次删除元素

[在网络抓取器上工作,我从页面上提取篮球统计数据并将其格式化为Node。这是我在“ stats”数组中使用的数据的示例:

[
  'School1',    'ACC',        '35',   '34',         '33.2',
  '2.5',        '4.8',        '.515', '1.1',        '1.5',
  '.685',       '1.4',        '3.2',  '.434',       '0.5',
  '0.7',        '.692',       '0.7',  '2.7',        '3.4',
  '3.6',        '1.5',        '0.9',  '0.8',        '1.3',
  '6.8',        '',           '9.30', 'School2',    'Big 12',
  '22',         '22',         '36.7', '5.6',        '11.1',
  '.504',       '3.2',        '5.5',  '.592',       '2.4',
  '5.6',        '.419',       '1.7',  '2.0',        '.822',
  '1.5',        '4.4',        '5.9',  '6.5',        '2.5',
  '0.7',        '2.8',        '1.3',  '15.2',       '',
  '10.07',      'School1',    '',     '57',         '56',
  '34.6',       '3.7',        '7.2',  '.509',       '1.9',
  '3.1',        '.621',       '1.8',  '4.2',        '.426',
  '1.0',        '1.2',        '.775', '1.0',        '3.4',
  '4.4',        '4.7',        '1.9',  '0.8',        '1.6',
  '1.3',        '10.1',       '',     '9.68'
]

“ SchoolX”数据点之后的数组中的每个项目代表该特定学校和年份的季节统计信息。我只想将School2中的数据包括在数组中,这是我为初始循环删除不必要的信息而准备的内容:

if (stats[0].includes("School2")) {
    playerObject.push({
        gp: stats[2],
        gs: stats[3],
        mpg: stats[4],
        fg: stats[7],
        tp: stats[9],
        ft: stats[11],
        rpg: stats[14],
        apg: stats[15],
        bpg: stats[16],
        spg: stats[17],
        ppg: stats[20]
    });
} else {
   // splice the input array of the first "season" data
    stats.splice(0, 28)
}  

这成功处理了阵列中的第一个“季节”不在School2的情况,并删除了数据。如何创建循环以遍历整个数组并删除与School2的季节不对应的值,同时将其余数据保留在数组中?

以下是预期的输出:

[
  'School2',    'Big 12',     '22',    22',         '36.7', 
  '5.6',        '11.1',       '.504', '3.2',        '5.5',  
  '.592',       '2.4',        '5.6',  '.419',       '1.7',  
  '2.0',        '.822',       '1.5',  '4.4',        '5.9',  
  '6.5',        '2.5',        '0.7',  '2.8',        '1.3',  
  '15.2',       '',           '10.07'
]

仅对应于School2的数据保留在数组中。预先感谢您的帮助。

回答如下:

假设每个学校确实有28个元素,请尝试如下操作:

data =[your data from above];

const chunk = (arr, size) =>
  Array.from({ length: Math.ceil(arr.length / size) }, (v, i) =>
    arr.slice(i * size, i * size + size)
  );
schools = chunk(data, 28);

for (school of schools) 
  if (school[0]=="School2")
    console.log(school);

注意:chunk部分为borrowed from here.

本文标签: 根据条件从数组中多次删除元素