Answer the question
In order to leave comments, you need to log in
How to sort an array with group separators added?
I want to ask a question, because of which the topics "How many such questions will be" appear, but I will ask.
I'm making a script that displays a list in alphabetical order, and I want the list to be displayed in the following order:
Letter
Alphabetical words starting with this letter, ie.
A
Adam
J
John
M
Mary
Mike
$scope.dis =
[{name:'John', anchor:'123'},
{name:'Mary' , anchor:'123'},
{name:'Mike' anchor:'123'},
{name:'Adam' anchor:'123'},"
Answer the question
In order to leave comments, you need to log in
I don't understand if this is the answer:
// сортируем
var sorted = $scope.dis.sort(function (a, b) {
return a.name > b.name? 1 : -1;
});
// собираем сам массив
var sortedWithGroups = sorted.reduce(function (res, a) {
// добавляем дополнительно букву перед первым словом на новую букву
// если это первое слово на эту букву
if (res.lastGroup !== a.name[0]) {
res.lastGroup = a.name[0];
res.push({name: a.name[0], group: true});
}
// добавляем саму ссылку
res.push(a);
return res;
}, []);
The algorithm is as follows:
1. Sort everything alphabetically.
2. Display words in a loop, while displaying the title letter only if it does not match the first letter of the previous word.
I use lodash/underscore for this kind of stuff.
_.sortBy(['a', 'b', 'c'], function(s){
return s.charCodeAt() * -1;
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question