Skip to content

Instantly share code, notes, and snippets.

@atomize
Last active September 12, 2018 16:59
Show Gist options
  • Save atomize/e66a42490f2c1aa92be0ff2ad18dff8b to your computer and use it in GitHub Desktop.
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.
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","&^%$"]
}
]
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