Last active
September 12, 2018 16:59
-
-
Save atomize/e66a42490f2c1aa92be0ff2ad18dff8b to your computer and use it in GitHub Desktop.
Groups an array of items alphabetically, putting items that start with numbers in a '0-9' group.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let arrayToGroup = ['Alpha','Alpha2','Centaur','Dudeman', 'Ladygirl', '888','999','&^%$']; | |
groupAlphaArray(arrayToGroup) | |
/****OUPUT****/ | |
[ | |
{ | |
"group":"A", | |
"children":["Alpha","Alpha2"] | |
}, | |
{ | |
"group":"C", | |
"children":["Centaur"] | |
}, | |
{ | |
"group":"D", | |
"children":["Dudeman"] | |
}, | |
{ | |
"group":"L", | |
"children":["Ladygirl"] | |
}, | |
{ | |
"group":"0-9", | |
"children":["888","999","&^%$"] | |
} | |
] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function groupAlphaArray(rawData) { | |
var numtest = new RegExp(/[^A-Za-z]/) | |
let data = rawData.reduce((r,e)=>{ | |
let group = e.charAt(0).toUpperCase(); | |
numtest.test(group)?group = '0-9':group; | |
if (!r[group]) { | |
r[group] = { | |
group, | |
children: [e] | |
} | |
} else { | |
r[group].children.push(e); | |
} | |
return r; | |
} | |
, {}) | |
let result = Object.values(data) | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment