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

时间:2018-11-26 13:48:22

标签: javascript arrays

我有一个数组,它具有不同且独特的错误,

[
 "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 个答案:

答案 0 :(得分:1)

您想要的数组中的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\',)]' ]