I have a list of object like this:
[
{"groups":["aaa"]},
{"groups":["bbb"]},
{"groups":["ccc"]},
{"groups":["ddd"]},
{"groups":["eee"]},
{"groups":["fff"]},
{"groups":["ggg"]},
{"groups":["hhh"]},
{"groups":["iii"]},
{"groups":["mmm", "mmm"]}
{"groups":["lll", "lll"]}
];
i want put all object with more that one groups at the end of the list in alphabetical order and keep the others with one groups, at beginning of the list without change the original order.
This is my code
var list = [
{"groups":["aaa"]},
{"groups":["bbb"]},
{"groups":["ccc"]},
{"groups":["ddd"]},
{"groups":["eee"]},
{"groups":["fff"]},
{"groups":["ggg"]},
{"groups":["hhh"]},
{"groups":["iii"]},
{"groups":["mmm", "mmm"]},
{"groups":["lll", "lll"]}
];
list.sort(function(a, b){
var aIsGroup = (a.groups.length > 1);
var bIsGroup = (b.groups.length > 1);
if (aIsGroup && !bIsGroup) {
return 1;
} else if (!aIsGroup && bIsGroup) {
return -1;
} else if(aIsGroup && bIsGroup){
return a.groups[0].toLowerCase().localeCompare(b.groups[0].toLowerCase());
}
return 0;
});
console.log(list);
You can see in the snippet the current output, but the expected output is:
[
{
"groups": [
"aaa"
]
},
{
"groups": [
"bbb"
]
},
{
"groups": [
"ccc"
]
},
{
"groups": [
"ddd"
]
},
{
"groups": [
"eee"
]
},
{
"groups": [
"fff"
]
},
{
"groups": [
"ggg"
]
},
{
"groups": [
"hhh"
]
},
{
"groups": [
"iii"
]
},
{
"groups": [
"lll",
"lll"
]
},
{
"groups": [
"mmm",
"mmm"
]
}
]