S
S
Sergey2015-04-04 20:51:06
JavaScript
Sergey, 2015-04-04 20:51:06

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'},"

What sequence of actions should the script have?
1) Sort the array alphabetically $scope.names = $scope.dis.sort();
Take an element, somewhere to write down the first character of each element names, and then compare with the next letter?
In general, what is the least expensive way?
This is by no means a task - I want exactly the algorithm

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexey Yaroshevich, 2015-04-05
@TsarS

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;
}, []);

As a result, sortedWithGroups has a sorted array grouped by letters.
ps Divided into variables only for the sake of comments. All this can be collected in several lines and reduce is called immediately after sort in one construct.
Links:
Array.prototype.sort: https://developer.mozilla.org/en-US/docs/Web/JavaS...
Array.prototype.reduce: https://developer.mozilla.org/en-US/ docs/Web/JavaS...

A
Andrey, 2015-04-04
@standy

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.

A
Alexey Pavlov, 2015-04-05
@joseperez

I use lodash/underscore for this kind of stuff.

_.sortBy(['a', 'b', 'c'], function(s){ 
    return s.charCodeAt() * -1;
});

In general, angularjs has a native $filter service. He can do it too.
https://docs.angularjs.org/api/ng/filter/orderBy

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question