Please write a function, input is a string, output array?

topic description

sources of topics and their own ideas

related codes

/ / Please paste the code text below (do not replace the code with pictures)

string

  1. A1, B1, C1, C1, C2, B2, A2, D1, D2, D3
  2. E1, E2, E3, F1, F2, F3
Special characteristics of

string type: each TOKEN in the string is alphanumeric. You need to do a function processing on the string to get the following result. In the
question, there are only two strings that conform to the above rules, and the strings that conform to the above rules are infinite.

string 1 result:
A--> {A1 recorder A2}
B--> {B1J B2}
C--> {C1J C2}
DLV-> {D1 Magi D2 D3}

string 2 result:
E--> {E1Part E2 E3}
F-> {F1Pert F2 F3}

what result do you expect? What is the error message actually seen?

Jun.18,2021

function toArray(str){
    str = str || ''
    str = str.split(',')
    var k,
        result = {}
    str.forEach(item=>{
        item = item.trim()
        k = item.replace(/\d+$/,'')
        result[k] ? result[k].push(item) : (result[k] = [item])
    })
    return result
}
toArray('A1,B1,C1,C2,B2,A2,D1,D2,D3')
//{"A":["A1","A2"],"B":["B1","B2"],"C":["C1","C2"],"D":["D1","D2","D3"]}
toArray('E1,E2,E3,F1,F2,F3')
//{"E":["E1","E2","E3"],"F":["F1","F2","F3"]}

'A1B1C1C2B2A2D1D2D3'.split('').reduce((s,v)=>{
    var _first = v[0];
    if(!s[_first]) s[_first] = [];
    s[_first].push(v)
    return s;
},{})

clipboard.png


take lodash as an example, use the groupBy function

let test = "A1B1C1C2B2A2D1D2D3";
let result = _.groupBy(test.split(''), item => item[0]);
console.log(result);

//
A: (2) ["A1", "A2"]
B: (2) ["B1", "B2"]
C: (2) ["C1", "C2"]
D: (3) ["D1", "D2", "D3"]
Menu