【问题标题】:Grouping array into one将数组分组为一个
【发布时间】:2020-01-04 10:57:40
【问题描述】:

有一个数组包含appointmentID(第一个值)和supperBillID(第二个值),用逗号分隔。 AppointmentID 将是唯一的,但 superBillID 只能在连续位置上相同。我想要的是一个包含所有appointmentID 值的数组,这些值具有相同的billingID,用逗号分隔。

我编写了以下代码,但没有得到正确的输出:

var fg = ['10000021,23', '10000022,23', '10000023,24', '10000024,25', '10000025,25', '10000026,25', '10000027,26', '10000028,27'];
var tab = [];
var gbl = 0;

for (var i = 0; i < fg.length; i++, gbl++) {
    var vb = fg[gbl].split(',')[1]; // Will use try catch here
    var mainAr = fg[gbl].split(',')[0];

    for (var j = i + 1; j < fg.length; j++) {
        if (vb == fg[j].split(',')[1]) {
            mainAr = mainAr + ',' + fg[j].split(',')[0];
            gbl++;
        }
        else {
            break;
        }
        tab.push(mainAr, vb);
    }
}

示例输入:

var input = ['10000021,23', '10000022,23', '10000023,24', '10000024,25', '10000025,25', '10000026,25', '10000027,26', '10000028,27'];

预期输出:

output = ['10000021,10000023',23]
         ['10000023',24]
         ['10000024,10000025,10000026',25]
         ['10000027',26]
         ['10000028',27]

【问题讨论】:

    标签: javascript arrays loops split append


    【解决方案1】:

    第一步,您可以使用Array.reduce()appointmentdID 值分组为Set(以避免appointmentID 的值重复),并使用billingID 作为分组键。

    然后,您可以将先前生成的对象的Array.map()entries 转换为最终所需的结构。在这里,我将假设您需要两种可能的输出之一:A) 一个数组数组,如您上次展示的那样,或 B) 一个字符串数组,其中输入的样式。

    var input = ['10000021,23', '10000022,23', '10000023,24', '10000024,25', '10000025,25', '10000026,25', '10000027,26', '10000028,27'];
    
    let output = input.reduce((acc, str) =>
    {
        const [appointmentID, billingID] = str.split(",");
        acc[billingID] = acc[billingID] || new Set();
        acc[billingID].add(appointmentID);
        return acc;
    }, {});
    
    // Map to array of arrays:
    let out1 = Object.entries(output).map(([k, v]) => [[...v].join(","), +k]);
    console.log("Array of arrays", out1);
    
    // Map to array of strings:
    let out2 = Object.entries(output).map(([k, v]) => [...v, k].join(","));
    console.log("Array of strings", out2);
    .as-console {background-color:black !important; color:lime;}
    .as-console-wrapper {max-height:100% !important; top:0;}

    另一个替代方案,不是那么通用,基于以下假设:“AppointmentID 将是唯一的,但 superBillID 可以是相同的仅在连续位置”可能是:

    var input = ['10000021,23', '10000022,23', '10000023,24', '10000024,25', '10000025,25', '10000026,25', '10000027,26', '10000028,27'];
    let output = [];
    
    for (let i = 0; i < input.length; i++)
    {
        const [appointmentID, billingID] = input[i].split(",");
        const len = output.length - 1;
    
        if (output[len] && output[len][1] === +billingID)
            output[len][0] += "," + appointmentID;
        else
            output.push([appointmentID, +billingID]);
    }
    
    console.log(output);
    .as-console {background-color:black !important; color:lime;}
    .as-console-wrapper {max-height:100% !important; top:0;}

    【讨论】:

      【解决方案2】:

      您可以reduce 数组,每个supperBillID 作为累加器中的键。如果supperBillID 已存在,请更新0 索引。否则,将密钥添加到累加器并将其设置为数组。使用Object.values()以数组形式获取值

      var fg = ['10000021,23', '10000022,23', '10000023,24', '10000024,25', '10000025,25', '10000026,25', '10000027,26', '10000028,27'];
      
      const merged = fg.reduce((acc, o) => {
        const [appId, billId] = o.split(',');
        if (acc[billId])
          acc[billId][0] += `,${appId}`;
        else
          acc[billId] = [appId, billId]
        return acc;
      }, {})
      
      const output = Object.values(merged);
      
      console.log(output)

      【讨论】:

        【解决方案3】:

        先将数组转换为方便的对象数组,然后根据描述的条件对数组进行归约

        const input = [
          "10000021,23",
          "10000022,23",
          "10000023,24",
          "10000024,25",
          "10000025,25",
          "10000026,25",
          "10000027,26",
          "10000028,27"
        ];
        
        const dataset = input.map(item => {
          const nodes = item.split(",");
        
          return {
            appointmentid: nodes[0],
            superbillid: nodes[1]
          };
        });
        
        const output = dataset.reduce((accumulator, current) => {
          const item = accumulator.find(
            element => element[element.length - 1] === current.superbillid
          );
        
          if (item !== undefined) {
            item.unshift(current.appointmentid);
          } else {
            accumulator.push([current.appointmentid, current.superbillid]);
          }
        
          return accumulator;
        }, []);
        
        console.log(output);

        要获取字符串数组,您可以尝试像这样在每个数组项上使用 map

        const recipient = output.map(item =&gt; item.join(',')));

        这将返回

        [
          "10000022,10000021,23",
          "10000023,24",
          "10000026,10000025,10000024,25",
          "10000027,26",
          "10000028,27"
        ]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-01-01
          • 2012-05-28
          • 2013-03-12
          相关资源
          最近更新 更多