代码之家  ›  专栏  ›  技术社区  ›  Hernan Humaña

如何在javascript中对数组进行分组?

  •  -1
  • Hernan Humaña  · 技术社区  · 6 年前

    [
     "ClientError('Bad Request: Not authorized to view user',)",
     "ConnectionResetError(104, 'Connection reset by peer')",
     "CursorNotFound('Cursor not found, cursor id: 195552090717',)",
     "CursorNotFound('Cursor not found, cursor id: 193743299994',)",
     "CursorNotFound('Cursor not found, cursor id: 194974042489',)"
    ]
    

    我只有3个错误,但自从 cursor id CursorNotFound

    我想得到这样的东西:

    [
        "ClientError('Bad Request: Not authorized to view user',)",
        "ConnectionResetError(104, 'Connection reset by peer')",
        "groupA": [
            "CursorNotFound('Cursor not found, cursor id: 195552090717',)",
            "CursorNotFound('Cursor not found, cursor id: 193743299994',)",
            "CursorNotFound('Cursor not found, cursor id: 194974042489',)"
        ]
    ]
    

    可以 indexof

    let allError = [];
     _array.forEach(element => allError.push(element.error));
    let uniq = Array.from(new Set(allError));
    console.log(uniq);
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Anouar Kacem    6 年前

    您想要的数组中的groupA应该是一个对象,或者应该是一个完整的字符串,这应该可以做到,但是有更好的方法

    var errors = [
         "ClientError('Bad Request: Not authorized to view user',)",
         "ConnectionResetError(104, 'Connection reset by peer')",
         "CursorNotFound('Cursor not found, cursor id: 195552090717',)",
         "CursorNotFound('Cursor not found, cursor id: 193743299994',)",
         "CursorNotFound('Cursor not found, cursor id: 194974042489',)"
        ]
    
    var cursorNotFound = [];
    var newErr = [];
    errors.forEach((element) => {
        if (element.includes('CursorNotFound')) {
            cursorNotFound.push(element);
        } else {
            newErr.push(element);
        }
    })
    
    newErr.push({
        "groupA": cursorNotFound 
    })
    // newErr.push("groupA: [" + cursorNotFound + "]")
    

    结果:

    [ 'ClientError(\'Bad Request: Not authorized to view user\',)',
      'ConnectionResetError(104, \'Connection reset by peer\')',
      { groupA:
         [ 'CursorNotFound(\'Cursor not found, cursor id: 195552090717\',)',
           'CursorNotFound(\'Cursor not found, cursor id: 193743299994\',)',
           'CursorNotFound(\'Cursor not found, cursor id: 194974042489\',)' ] } ]
    

    完整字符串组A的结果:

    [ 'ClientError(\'Bad Request: Not authorized to view user\',)',
      'ConnectionResetError(104, \'Connection reset by peer\')',
      'groupA: [CursorNotFound(\'Cursor not found, cursor id: 195552090717\',),CursorNotFound(\'Cursor not found, cursor id: 193743299994\',),CursorNotFound(\'Cursor not found, cursor id: 194974042489\',)]' ]